Reputation: 1655
Tryed to compare the difference between different $watch argument passing:
Code:
angular.module('app', [])
.controller( 'someCtrl', [ '$scope', function ( $scope ) {
$scope.someVar = 'a';
}])
.directive( 'dirName', [ function() {
var directive = {};
directive.restrict = 'AE';
var link = function ( scope, element, attrs ) {
console.log('link!');
scope.$watch( 'someVar', function() {
console.log('var-string!');
});
scope.$watch( scope.someVar, function () {
console.log ('var with scope!');
} );
scope.$watch( function () {
return scope.someVar;
}, function () {
console.log('function returns the var!');
} );
}
directive.compile = function ( scope, element, attr ) {
console.log('compile!');
return link;
}
return directive;
}]);
Html:
<body ng-app="app">
<div ng-controller="someCtrl">
<div dir-name>{{someVar}}</div>
<button ng-click="someVar='b'">b!</button>
</div>
Onload/parse we have:
compile!
link! (this parts is quite clear for understanding)
var-string!
var with scope!
function returns the var
On click:
var-string!
function returns the var!
Can someone explain the difference between different setting types? What is preferred/faster/different cases/etc?
Upvotes: 0
Views: 30
Reputation: 1591
Strings are evaluated against the scope during an apply/digest cycle to check for changes. Functions are simply called during an apply/digest cycle to check for changes. Therefore, passing a string s
is equivalent to passing a function like
function () {
return $scope.$eval(s);
}
passing $scope.someVar
will result in one of the above depending on whether $scope.someVar
evaluates to a string or a function. It will not set up a watch for the someVar
variable unless $scope.someVar
is the string "someVar"
or a function which returns $scope.someVar
.
Upvotes: 1