范围变量更改时如何更新指令?

时间:2017-01-26 22:23:00

标签: angularjs angularjs-directive

如果它包含一个特定的关键字,我创建了一个突出显示div中文本的指令:如下所示

    angular.module('app', []).directive('words', function() {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          var words = element.attr('words').split(' ');
          
          for(var i=0; i<words.length; i++) {
            var r = new RegExp(words[i], 'ig')
            element.html(element.html().replace(r, '<span class="highlight">' + words[i] + '</span>'));
          }
        }
      };
    })
  .highlight {
      background-color: yellow;
    }
  
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="app" words="automobile physiology crime">
     The dentist travels every coverage.
     The talent pumps opposite the automobile. 
     The poet shies away under a frightening day.
     The innovative physiology breezes above the ideology.
     A manned waste fusses next to the hardback crime.
     The changing conflict recovers in my fewer sermon.
     </div>

但是,div的关键字和内容会更新,因为它们包含scope个变量。在这种情况下,文本不会突出显示。如何更新范围变量更改的指令?

这是我的真实代码

<div ng-app="app" words="{{search.keywords}}">{{search.results}}</div>

2 个答案:

答案 0 :(得分:3)

首先删除插值:

<!--REMOVE interpolation
<div ng-app="app" words="{{search.keywords}}">{{search.results}}</div>
-->

<div ng-app="app" words="search.keywords">{{search.results}}</div>

然后使用观察者:

angular.module('app', []).directive('words', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
       scope.$watch(attrs.words, function(newValue) {
          if (!newValue) return;

          var words = newValue.split(' ');

          for(var i=0; i<words.length; i++) {
            var r = new RegExp(words[i], 'ig')
            element.html(element.html().replace(r, '<span class="highlight">' + words[i] + '</span>'));
          };
       });
    }

  };
})

有关详细信息,请参阅{{3}}

答案 1 :(得分:0)

使用

return {
  restrict: 'A',
  scope: {
    words: '='
  }
}
在你的指令中

进行双向绑定

并改变这个

<div ng-app="app" words="{{search.keywords}}">{{search.results}}</div>

<div ng-app="app" words="search.keywords">{{search.results}}</div>

并且还改变了这部分

var words = element.attr('words').split(' ');

var words = scope.words.split(' ');