angularjs - Two way binding, $watch, isolate scope not working together -
please refer fiddle questions. http://jsfiddle.net/aqr55/
1) why watch attached isolate scope property - bidirectionally bound parent property, not triggering on changing parent scope property.
in fiddle, below metioned watch not getting triggered, on changing parent scope property bound.
$scope.$watch('acts', function(neww ,old){ console.log(neww) })
2) ng-click="addaction()" addaction="addaction()"
. can code put in more elegant way? because, perform action in isolated scope, seems need set bidirectional binding , attach ng-click.
3)can declare methods inside isolated scope shown below? if this, i'm getting .js error.
<isolate-scope-creating-cmp ng-click="isolatecmpclickhandler()"></isolate-scope-creating-cmp> scope:{ isolatecmpclickhandler:function(){ //if this, i'm getting .js error } }
question 1.
since adding item acts
array, need set third parameter in $watch() true
$scope.$watch('acts', function (neww, old) { console.log(neww) }, true);
demo: fiddle
question 2.
since there isolated scope, need call $parent
scope's function
<input type="button" bn="" acts="acts" ng-click="$parent.addaction()" value="add action" />
demo: fiddle
question 3.
yes can, need use controller
animateappmodule.directive('bn', function () { return { restrict: "a", scope: { acts: '=' }, link: function ($scope, ielement, iattrs) { $scope.$watch('acts', function (neww, old) { console.log(neww) }, true) }, controller: function($scope){ $scope.dosomething = function(){ console.log('do something') } } } })
demo: fiddle
an overall solution like
<input type="button" bn="" acts="acts" addaction="addaction()" value="add action" />
js
animateappmodule.controller('tst', function ($scope) { $scope.acts = []; $scope.addaction = function () { $scope.acts.push({ a: "a,b" }) } }) animateappmodule.directive('bn', function () { return { restrict: "a", scope: { acts: '=', addaction: '&' }, link: function ($scope, ielement, iattrs) { $scope.$watch('acts', function (neww, old) { console.log(neww) }, true); ielement.click(function(){ $scope.$apply('addaction()') }) } } })
demo: fiddle
Comments
Post a Comment