简体   繁体   中英

How to watch change of variable from inside a directive?

I have a custom directive that is coded like this:

 angular.module('client.core.directives')
     .directive('containerlayout', function () {

         function link(scope, el, attr) {
            scope.$watch(['xdim', 'ydim', 'numOrder'], function () {
                    console.log("Watch Xdim/Ydim/numOrd change");
                    // do something when these changesd
                }, true);
            scope.$watch('labels', function (labels) {
                    // do something when labels array changes
                }, true);

            } 

         return {
             link: link,
             restrict: 'E',
             scope: { geometry: '=geometry', xdim: '=xdim',
               ydim: '=ydim', numOrder: '=numorder', labels: '=labels',
               states: '=states', emptyToSkipped: '=emptytoskipped' }
    };

and I have the following declaration:

   <containerlayout geometry="rect" xdim="cont.xdim" 
     ydim="cont.ydim" numorder="1" labels="cont.labels"
     states="cont.states" emptytoskipped="emptytoskipped" 
     class="ng-isolate-scope"></containerlayout>

but when I change,say the $scope.cont.xdim or some other variables, nothing happens and watches are not firing.

Note that xdim and ydim are integers and labels is array.

How I should I declare things in directive so it will watch the variables? do they need to be initialized first thing in the controller for successfull work? I need to remain in isolated scope if possible.

$watch('propertyName', func) watches for only one $scope.propertyName .

If you want to watch for several properties, you need $watchCollection('[propertyName, anotherPropertyName]', func) .

 scope.$watchCollection('[xdim, ydim, numOrder]', function (valuesArray) {
     console.log("Watch Xdim/Ydim/numOrd change", valuesArray);
 }, true);

Does labels watcher trigger in your example? It should, because it is only one property containing an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM