I've come across this way of isolate binding
specification:
scope: {
property: "=*"
}
What does the asterisk mean here? Can someone please provide an example?
The isolate binding with
=*
is to shallow watch for the change in the collection.
Let me explain a bit:
Normally watchCollection variables we use in the scripts like below:
$scope.arr = ['foo', 'bar', 'lorem', 'ipsum'];
$scope.arrCount = 4;
$scope.$watchCollection('arr', function(new, old) {
$scope.arrCount = new.length;
});
But what if you want to do object binding in html attribute itself?
<my-directive my-attr="arr"><!--$scope.arr-->
And, if you do this:
scope: {
myAttr: "=*"
}
Now, the directive attributes are assigned as it should shallow watch. And the use of watchCollection is good of use this time.
So, the =*
is to be used when we need to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use =* or =attr (=? or =*?attr if the property is optional) as described in the docs.
Although, we can use =
for watchCollection to deeply watch the object or array we can use =*
for the same. But only difference is that using =*
method the collection becomes true and when collection becomes true angularjs use the $watchCollection to remove the watcher and it uses the $watch to remove the watcher when collection is false:
if (definition.collection) { //using `=*`
removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
} else { //using `=`
removeWatch = scope.$watch($parse(attrs[attrName],
parentValueWatch), null, parentGet.literal);
}
So, when you want to shallow watch for the collection then you need to use =*
.
The asterisk is used to change the default watch behavior.
From the angular docs:
By default, the $watch method is used for tracking changes, and the equality check is based on object identity. However, if an object literal or an array literal is passed as the binding expression, the equality check is done by value (using the angular.equals function). It's also possible to watch the evaluated value shallowly with $watchCollection: use =* or =attr (=? or =*?attr if the attribute is optional).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With