简体   繁体   中英

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. As I said, this value is the value of a custom directive: auto-focus="{{isFocused}}"

I've created a simple plunker to show my problem, any help would be great.

Angular - listening to binding changes in directive executed by controller

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. This is described in the angularjs documentation: 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. Here's an updated 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"

Change it to:

focus-on="ifFocused"

Then your code works fine.

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