简体   繁体   中英

Angualrjs - `$watch` not working for `this` declared controller object change

I am trying to $watch an object from controller. But it's not working. here is my controller code :

angular.module('myapp',[]).controller('myController', function(){

var vm = this;

vm.name = "myname"

})

In directive :

    angular.module('myapp',[]).directive('myDirective',function(){
    return{
    link:function(scope, element, attrs){
        scope.$watch('vm.name', function(nv,ov){
         console.log(nv) //not working
    }
    }
    }
})

what is missing here? any one help me?

if I am not correct, help me to correct me here

Live URL

I have updated my code like this: it works for me

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  var vm = this;

  vm.name = "no name";

  vm.update = function(){

    vm.name = "new Name";

  }

});

app.directive('myDirective', function(){

  return{

    link: function(scope, element, attrs){

     scope.$watch('Ctrl.name', function(nV, oV){

       console.log( nV );

     })

    }

  }

})

You'll need to specify which controller to use in your directive

angular.module('myapp',[]).directive('myDirective',function(){
    return {
        controller: myController,
        controllerAs: 'vm', // this will let you use vm.name in any bindings
        link:function(scope, element, attrs){
            scope.$watch('vm.name', function(nv,ov){
                console.log(nv) //not working
            }
        }
    };
})

function myController(){

    var vm = this;

    vm.name = "myname"
});

EDIT

Given your Plunker this solution wouldn't work for what you need

Check this Plunker instead

"vm.*" will work when both the Controller and the View follow the same "controller as". You are using the same scope of controller inside the directive. You need to $watch using the Controller as alias.

ng-controller="MainCtrl as Ctrl"
scope.$watch('Ctrl.name', function(nV, oV){
    console.log( nV );
})

See this Plunker .

Ben Nadel has written a nice article on this.

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