javascript - Is the angular scope binding &(ampersand) a one time binding? -
is angular scope binding &(ampersand) 1 time binding? see referred one-way binding, one-time?
let's have:
<my-custom-directive data-item="item" />
and directive declared follows:
.directive('mycustomdirective', [ '$log', function ($log) { return { restrict: 'e', templateurl: '/template.html', scope: { dataitem: '&' } controller: function ($scope) { // .... } }])
the reason i'm asking if binding one-time because seems i'm observing, is. if item
in parent scope updated, 1 in directive not updated.
am right in saying binding 1 time?
to achieve want, directive keeps copy without affecting parent scope's item -- did this:
.directive('mycustomdirective', [ '$log', function ($log) { return { restrict: 'e', templateurl: '/template.html', scope: { dataitemoriginal: '=' }, link: function ($scope) { $scope.$watch('dataitemoriginal', function () { $scope.dataitem = window.angular.copy($scope.dataitemoriginal); }); }, controller: function ($scope) { //.... } }])
is proper or there better way?
there better way. current solution setting 3 watches - 2 created using "=" binding, , $watch create make copy. $watches relatively expensive.
here alternative doesn't create watches:
.directive('mycustomdirective', [ '$log', function ($log) { return { restrict: 'e', templateurl: '<div ng-click="clicked()">click me current value</div>', scope: { item: '&' }, controller: function($scope) { $scope.clicked = function(){ alert(item()); //item() returns current value of parent's $scope.item property } $scope.val = item(); //val initial value of $parent.item $scope.val = 42; //$parent.item unaffected. } }])
& highly misunderstood. while can used passing functions isolated scope, is:
provides way execute expression in context of parent scope
it generates function in directive that, when called, executes expression in context of parent scope. expression not have function or function call. can valid angular expression.
so in example:
<my-custom-directive data-item="item"></my-custom-directive> scope: { item: '&' }
$scope.item in directive function can call in controller or in template. invoking function return object referenced "item" in parent scope. there no binding & - no watches used.
where "one-way-binding" misnomer comes in using &, directive cannot change value of $parent.item, when using "=", directive, virtue of $watches created, can. not "one time", either, since it's not technically bound @ all.
since mechanism angular uses generate function involves $parse, possible directive pass in "locals" override values in expression values directive. so, in directive controller, if did:
item({item: 42})
it return 42, regardless of value of item in parent scope. feature makes & useful executing function expressions on parent scope data directive.