AngularJS指令在元素具有绑定值的情况下不起作用

AngularJS directive not working where element have a binding value

本文关键字:情况下 不起作用 绑定 指令 元素 AngularJS      更新时间:2023-09-26

我有一个指令来显示/隐藏基于某些内容的元素。但是当元素绑定到某个值时,它不起作用。我希望我的指令在这种情况下仍然有效。

angular.module("app", [])
.controller('ctrl', function ($scope){
  $scope.color = "red";
})
.directive('xred', function() {
  return {
    link: function(scope, element, attrs) {
      var role = 0;
      if (role === 0) element.css('display', 'none');
    }
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  
  <!-- where I hard code 'blue', xred directive is working-->
  <span xred style="color: blue"> Blue (should hide) </span>
  
  <!-- where I bind color, xred directive is not working.-->
  <span xred style="color: {{color}}"> Red (should hide) </span>
  
</div>

不确定我是否理解您的问题,但使用ngStyle它似乎有效:

angular.module("app", [])
.controller('ctrl', function ($scope){
  $scope.color = "red";
})
.directive('xred', function() {
  return {
    link: function(scope, element, attrs) {
      var role = 0;
      if (role === 0) element.css('display', 'none');
    }
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  
  <!-- where I hard code 'blue', xred directive is working-->
  <span xred style="color: blue"> Blue (should hide) </span>
  
  <!-- where I bind color, xred directive is not working.-->
  <span xred ng-style="{color: color}"> Red (should hide) </span>
  
</div>

因为你使用 Angular 的插值设置了一个样式,所以它现在会跟踪它的属性值本身,你通过直接触摸元素所做的任何更改都将随时被 Angular 覆盖(比如设置 display: none基本上只是修改style属性,然后被 color: {{color}} 覆盖(。

因此,在您的情况下,尽量不要直接写入style属性,而是使用ngStylengClass

我只在您的示例中添加了类 hidden 并添加/删除它以显示/隐藏您的元素。

angular.module("app", [])
.controller('ctrl', function ($scope){
  $scope.color = "red";
})
.directive('xred', function() {
  return {
    link: function(scope, element, attrs) {
      var role = 0;
      if (role === 0) {
          element.addClass('hidden');
      }
    }
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<style>
  .hidden { display: none; }
</style>
<div ng-app="app" ng-controller="ctrl">
  
  <!-- where I hard code 'blue', xred directive is working-->
  <span xred style="color: blue"> Blue (should hide) </span>
  
  <!-- where I bind color, xred directive is not working.-->
  <span xred style="color: {{color}}"> Red (should hide) </span>
  
</div>