How can I watch multiple interpolated attributes in a directive?

I don’t understand how to look at several attributes at the same time in the link function, so I create an object with all the parameters, and I follow it. But I noticed that the attribute in the link function is a string, not an object, so I use angular.fromJson (val).

The whole example I found just uses one parameter

Could you explain how to look at several attributes?

thanks

EDIT : I cannot use the attrs parameter because I need to bind attributes, i.e. They need interpolation. for example

<ul class="thumbnails"> <li class="span3" ng-repeat="image in currentSizeInfo.images" > <upload-file info = "{{getInfo($index)}}" foo="foo$index" ></upload-file> </li> </ul> 

I think I need to use $ watch

 link:function (scope, element, attrs ) { scope.$watch('info', function (val) { // if info is and foo is .... do all the stuff }) } 
+8
javascript angularjs angularjs-directive
source share
1 answer

I'm not sure I fully understand your question, so please correct me if I misunderstand. Just want to infer values ​​from multiple attributes into your directive? So say you have HTML like this:

 <my-directive attr1="data1" attr2="data2" attr3="data3" /> 

And you want to get the values ​​of these different attributes? In the communication function, you simply use the attrs parameter. For example:

 link: function(scope, element, attrs) { var foo1 = attrs.attr1; var foo2 = attrs.attr2; var foo3 = attrs.attr3; } 

You can also use the scope property in the directive to automatically bind attributes to your scope. See their directive documentation . So something like this:

 scope: { attr1: '@', attr2: '@', attr3: '@' } 

And then these properties automatically fall into your area. However, as I found out , these values ​​are not always in the area when you expect. That way you can use the $watch function to do what you need. Something like:

 link: function(scope, element, attrs) { scope.$watch("attr1", function () { if (scope.attr1) { //stuff with attr1 } } scope.$watch("attr2", function () { if (scope.attr2) { //stuff with attr2 } } //.... } 

If you need to use them all together at the same time, you can use the function for the first parameter of $watch , which returns a string that will be different when they are all there, and then put your logic in the function, which is the second parameter. So something like this:

 link: function(scope, element, attrs) { scope.$watch(function () { if (scope.attr1 && scope.attr2 && scope.attr3) { return "allSet"; } else { return ""; } }, function (newVal) { if ("allSet" == newVal) { //do stuff with all the properties } }); } 

If you want to link objects in your scope, you can use '=' instead of '@'. Another option is "&" which evaluates the function in the parent area. All of this is explained in the above documentation.

+11
source share

All Articles