控制器和指令之间的范围共享

时间:2021-11-24 13:36:49

I have some weird behavior on a simple scope variable that do not enter into the watcher when i change its content :

我在一个简单的范围变量上有一些奇怪的行为,当我更改其内容时,它不会进入观察者:

$scope.test = "test";
$scope.$watch('test', function (newVal, oldVal) {
    console.log("watcher=>"+newVal);
});

but when i pass an object it works :

但当我传递一个物体时它起作用:

$scope.test = {title: "test"};
$scope.$watch('test.title', function (newVal, oldVal) {
    console.log("watcher=>"+newVal);
});

I'm unable to reproduce this behavior on a fiddle : http://jsfiddle.net/pvYSu/33/

我无法在小提琴上重现这种行为:http://jsfiddle.net/pvYSu/33/

EDIT :

I reproduced my problem in this fiddle :http://jsfiddle.net/pvYSu/34/ I think it's related with a bad use on Angular so if someone can find and explain me what i've missed ;)

我在这个小提琴中重现了我的问题:http://jsfiddle.net/pvYSu/34/我认为这与Angular上的错误使用有关,所以如果有人能找到并解释我错过了什么;)

1 个解决方案

#1


2  

All you had to do was to use ng-model in the directive's template and it works as expected.

您所要做的就是在指令的模板中使用ng-model,它按预期工作。

http://jsfiddle.net/pvYSu/35/

<div>
    Name: <input type="text" ng-model="customerInfo.name" />
    Address: {{customerInfo.address}}
</div>

You also do not actually need an isolated scope for this.

您实际上也不需要一个孤立的范围。

http://jsfiddle.net/pvYSu/36/

#1


2  

All you had to do was to use ng-model in the directive's template and it works as expected.

您所要做的就是在指令的模板中使用ng-model,它按预期工作。

http://jsfiddle.net/pvYSu/35/

<div>
    Name: <input type="text" ng-model="customerInfo.name" />
    Address: {{customerInfo.address}}
</div>

You also do not actually need an isolated scope for this.

您实际上也不需要一个孤立的范围。

http://jsfiddle.net/pvYSu/36/