Angular Custom Directive Change Attribute Value

Strive to find the best way to observe attribute changes that will ideally be updated based on a keystroke event bound to an area in the parent controller

I would like each "instance" of the directive to have its own hasFocus property, which should be changed by updating the attribute value for example.

<menu has-focus="{{ true }}" ></menu> <menu has-focus="{{ false }}" ></menu> <menu has-focus="{{ false }}" ></menu> 

template:

 <div class="menu"> <ul> <li ng-repeat="option in menu.options" ng-class="{ 'focused' : hasFocus }" tabindex="{{ $index }}"> <div class="icon">{{ $index+1 }}</div> </li> </ul> 

and therefore, only one directive can have a value of "true" at any given time.

I have a custom directive

 .directive('menu', function() { restrict : 'E', templateUrl : 'partials/menu-left.html', replace : true, scope : { hasFocus : '@' }, link : function( $scope, element, attrs ) { attrs.$observe('hasFocus', function(value) { console.log(value); }); } }) 

but can not seem to be extracting the value from the $ observ method tried using $ watch, but still did not work not sure what i am doing wrong!

+6
source share
1 answer

if you use the @ binding, you may have to use $ watch as follows:

 $scope.$watch(function(){ return attrs.hasFocus; }, function(val) { $scope.hasFocus = val; }); 

if this does not work, or if you prefer two-way binding with = :

 <menu has-focus="true" ></menu> 

and

 .directive('menu', function() { restrict : 'E', templateUrl : 'partials/menu-left.html', replace : true, scope : { hasFocus : '=' }, link : function( $scope, element, attrs ) { // $scope.hasFocus holds true/false } }) 

I think two-way binding is better, especially with Boolean ones, because if you only need to control how the DOM looks, you won’t even have to follow the changes, you just need to connect $ scope.hasFocus to the DOM somewhere (ng- show, ng-switch, etc.)

EDIT: yes, I just noticed your pattern, so if you use two-way snapping ( = ) you don't need a clock

+1
source

Source: https://habr.com/ru/post/980711/


All Articles