简体   繁体   English

Angular - 监听由控制器执行的指令中的绑定更改

[英]Angular - listening to binding changes in directive executed by controller

I'm attempting to watch a custom directive attribute value inside the directive. 我正在尝试在指令中查看自定义指令属性值。 This value is a variable binding from a controller. 此值是来自控制器的变量绑定。 The variable is a boolean and is updated via an action in the controller. 变量是布尔值,并通过控制器中的操作进行更新。

I can see that I'm updating this value in the controller action correctly through console.logs but I cannot seem to get the directive to watch for changes to this value. 我可以看到我正在通过console.logs正确更新控制器操作中的这个值,但我似乎无法获得指令来监视此值的更改。 As I said, this value is the value of a custom directive: auto-focus="{{isFocused}}" 正如我所说,这个值是自定义指令的值:auto-focus =“{{isFocused}}”

I've created a simple plunker to show my problem, any help would be great. 我已经创建了一个简单的plunker来显示我的问题,任何帮助都会很棒。

Angular - listening to binding changes in directive executed by controller Angular - 监听由控制器执行的指令中的绑定更改

http://plnkr.co/edit/QwwFCQPN7L7nwuthH0CJ?p=preview http://plnkr.co/edit/QwwFCQPN7L7nwuthH0CJ?p=preview

In order to watch for changes in an attribute that has an interpolation you'll need to use $attrib.$observe instead of $scope.$watch. 为了观察具有插值的属性的变化,您需要使用$ attrib。$ observe而不是$ scope。$ watch。 This is described in the angularjs documentation: http://docs.angularjs.org/api/ng/service/$compile#Attributes 这在angularjs文档中有描述: http ://docs.angularjs.org/api/ng/service/$compile#Attributes

Also, you're comparing focusVal to true, but you're passing it as a string through the attribute. 此外,您将focusVal与true进行比较,但您将其作为字符串通过该属性传递。 Here's an updated plunker: http://plnkr.co/edit/e8ZaBM?p=preview 这是一个更新的plunker: http ://plnkr.co/edit/e8ZaBM?p = preview

In the focus-on directive, you have: 在焦点指令中,您有:

focus-on="{{isFocused}}"

This makes your directive actually watch what isFocus contains - which is "false" 这使你的指令实际上观察了isFocus包含的内容 - 这是“假的”

Change it to: 将其更改为:

focus-on="ifFocused"

Then your code works fine. 那你的代码工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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