Saturday, 15 May 2010

angularjs - Why are mouse events from my directive not reflected in the view? -



angularjs - Why are mouse events from my directive not reflected in the view? -

here illustration fiddle. please open console first.

it's little long, explain: you'll see 2 divs. 1 "regular", other created via directive. both have click event handlers (added via ng-click).

clicking regular (non-directive) div expect - appropriate variables in scope set , see in view (top 2 lines in output show id , top of div clicked).

the problem when clicking directive div. these variables not updated. know i'm misunderstanding scope of directive, confusing me log messages printed (open console when this). clicks registered, , controller's scope does set variable values, can see in console.

yet html not update - seek clicking 1 div, other, , go , forth, , you'll see.

what missing here?

code (please don't set off length!):

<div ng-app="myapp"> <div ng-controller="mycontroller"> top of div clicked = {{top}}.<br/> id of div clicked = {{lastid}}.<br/> <div id="notadirective" class="myclass" ng-click="update($event)"> not directive. click me. </div> <my-div element-id="isadirective" cls="myclass"> i'm directive. click me. </my-div> </div> angular.module('components', []) .controller('mycontroller', function ($scope) { $scope.lastid = ''; $scope.top = ''; $scope.update = function (event) { var mydiv = getfirstmyclassancestor(event.target); var style = window.getcomputedstyle(mydiv); $scope.top = style.top; $scope.lastid = mydiv.id; console.log("you clicked " + $scope.lastid + " , top " + $scope.top); } function getfirstmyclassancestor(element) { while (element.classname.indexof('myclass') < 0) { element = element.parentnode; } homecoming element; } }).directive('mydiv', function () { homecoming { restrict: 'e', replace: true, transclude: true, controller: 'mycontroller', scope: { cls: '@', elementid: '@' }, template: '<div id="{{elementid}}" class="{{cls}}" ng-click="update($event)"><div ng-transclude></div></div>' } }); angular.module('myapp', ['components']) .myclass { background-color: #da0000; position: absolute; } #isadirective { top: 300px; } #notadirective { top: 100px; }

in case of directive assigned controller mycontroller gets scope of directive , not scope of div expect. added log statement different scope ids:

http://jsfiddle.net/6zbkp/4/

if want update outer or parent scope have utilize binding this:

scope: { cls: '@', elementid: '@', callback: '=' },

then bind update function in directive:

<my-div element-id="isadirective" cls="myclass" callback="update"> i'm directive. click me. </my-div>

and phone call callback in directive:

template: '<div id="{{elementid}}" class="{{cls}}" ng-click="callback($event)"><div ng-transclude></div></div>'

see http://jsfiddle.net/6zbkp/5/

angularjs angularjs-directive angularjs-scope angularjs-ng-click

No comments:

Post a Comment