查看自定义指令中的属性-AngularJS



简要背景:我正在尝试编写一个指令,该指令将侦听引导程序下拉菜单的aria扩展属性,因为一旦其值变为false,我想做一些事情。据我所知,如果您想监视元素内部的类更改,这就是"angularJS"方式。

aria扩展类在这个img元素中。我的指令的名称是覆盖监视器

<img ng-init="displayMainMenu()" overlay-monitor id="nav-burger" uib-dropdown-toggle ng-disabled="disabled" ng-click="sMainMenu=true; isSubMenu=resetMenu(); getLinks(); bStopPropagation=true;" src="img/burger.png">

我真正想让它做的是,如果展开的aria变成false,就关闭我在页面上的不透明覆盖。但现在,我只是想触发一个警报,看看我做得是否正确:

app.directive('overlayMonitor', function () {
return {
    restrict: 'A',
    scope: { ariaExpanded: '@' },
    link: function ($scope, element, attrs) {
        if (element.attrs('aria-expanded') == "true") {
            alert('directive');
        }
    }
}
});

当我测试它时,警报没有显示。:(

我做错了什么?

请告知。非常感谢。

附言我忘了提。我们不允许使用jQuery。再次感谢您的回复!


编辑:在阅读了$watch之后,我尝试了以下代码:

app.directive('overlayMonitor', function () {
return {
    restrict: 'A',
    scope: { ariaExpanded: '@' },
    link: function ($scope, element, attrs) {
        $scope.$watch(function () {
            if (!attrs.ariaExpanded) {
                alert('false');
            }
            else {
                alert('true');
            }
        });
    }
}
});

好消息是警报突然出现了。坏消息是警报只说"假"。它从未发出警报("true")。:/

您可以这样使用:

if (attrs.ariaExpanded) { // instead of element.attrs('..')
   alert('directive');
}

函数link在呈现指令时执行一次。

因此,要跟踪变量中的更改,需要使用$watch

尝试以下操作:

app.directive('overlayMonitor', function () {
return {
  restrict: 'A',
  scope: { ariaExpanded: '@' },
  link: function (scope, element, attrs) {
    scope.$watch(function(){ return attrs.ariaExpanded; },
    function(val){
      if (!val) {
         alert('directive');
      }
    });
 }
}
});

最新更新