Angular 自定义指令改变属性值

Angular Custom directive change attribute value

努力寻找监视属性更改的最佳方法,理想情况下,它会根据按键事件进行更新,绑定到父控制器中的范围

我希望指令的每个 'instance' 都有自己的 'hasFocus' 属性,可以通过更新属性值来更改 例如

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

模板:

<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>

因此在任何时候只有 1 个指令的值等于 'true'。

我有一个自定义指令

.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);
     });
  }

}) 

但似乎无法从 $observe 方法中提取值 尝试使用 $watch 但仍然没有用 不确定我做错了什么!

如果您使用 @ 绑定,您可能必须像这样使用 $watch:

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

如果这不起作用,或者如果您更喜欢使用 = 进行双向绑定:

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

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

}) 

我认为双向绑定更好,尤其是对于布尔值,因为如果你只需要它来控制 DOM 的外观,你可能甚至不需要观察变化,你只需要将 $scope.hasFocus 插入 DOM 某处(ng-show、ng-switch 等)

编辑:是的,我刚刚注意到您的模板,所以如果您使用双向绑定 (=),则不需要手表