简体   繁体   中英

Angular $watch not triggering

We have one controller and one directive. In the controller's $scope there is modules array that contains some objects.

$scope.modules = [
   {title: 'demo'},
   {title: 'demo 2'},
   {title: 'demo 3'},
];

I am creating directive like this:

var popup = angular.element('<module-popup module="module"></module-popup>');
$compile(popup)($scope);

Listening to controller's $scope change:

$scope.$watch('title', function() {
    console.log('Controller changed');
}, true);

When page loads I see in console: Controller changed

But when I am trying to change these values manually - in console the are no records BUT at the screen i see correct values.

<h2>{{ module.title }}</h2>

$scope.$apply() throws an error

What am I doing wrong? Thanks

you're watching title but that isn't in your scope, the scope your trying to watch is modules.title or simply modules

  $scope.$watch('modules', function() {
        console.log('Controller changed');
    }, true);

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