Kuan
Kuan

Reputation: 11389

How to watch variable in a scope of controller which use several names in Angular

All:

I wonder if I use a controller in template with "as", but give it different alias in different places, I wonder how can I watch it?

Like:

app.controller("main", function(){
this.name = "hello";
})

And the template is like:

<div ng-controller="main as m1">
{{m1.name}}
</div>
<div ng-controller="main as m2">
{{m2.name}}
</div>
<div ng-controller="main as m3">
{{m3.name}}
</div>

I wonder what should I use to be watched?

$scope.$watch("m1.name", function(){});
$scope.$watch("m2.name", function(){});
$scope.$watch("m3.name", function(){});

Upvotes: 0

Views: 30

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Use a watch function:

app.controller("main", function($scope){
     this.name = "hello";
     var vm = this;
     function watchFn() {
         return vm.name;
     });
     $scope.$watch(watchFn, function(newValue) {
         console.log("name="+newValue);
     }); 
})

Upvotes: 1

Related Questions