【问题标题】:ngModel reference in directive called multiple time by view指令中的 ngModel 引用被视图多次调用
【发布时间】:2016-11-13 16:54:52
【问题描述】:
  1. 我在同一个视图中使用了两次指令。
  2. 在每个指令中,我调用一个带有字段和 ul 列表的模板。
  3. 当用户写东西时,我调用 API 返回一个 结果数组。
  4. 此数组用于通过 ng-repeat (ul) 显示列表。

问题: 如果用户在第一个加载的字段(第一个指令)中写入内容,则调用的 ng-repeat 在第二个指令中。

<div style="padding: 20px;">
    <p>First directive :</p>
    <span search-box ng-model="toto"></span>
    <hr>
    <p>Second directive :</p>
    <span search-box ng-model="titi"></span>
</div>

myApp.directive('searchBox', [function() {
return {
    restrict: 'A',
    scope: {
      model: '=ngModel',
    },        
    template: ''
    +'<div>'
    +       '<input type="text" ng-model="model" />'
    +       '<ul style="background-color:#e1e1e1; width: 142px; padding: 15px;" ng-show="cities.length">'
    +'          <li ng-repeat="city in cities">'
            +'                  {{city.label}}'
    +'          </li>'
    +     '</ul>'
    +'</div>',
    replace: true,
    transclude: true,
    link: function(scope, element, attrs, ngModel) {

                    scope.cities = [];

                    scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) search(newValue) });

                    search = function(input) {
                scope.cities = [
              {label: 'Paris'}, 
              {label: 'London'}, 
              {label: 'New York'}, 
              {label: 'Berlin'}, 
              {label: 'Lisbonne'}
            ];
        };
    }
}

http://jsfiddle.net/hNTrv/10/

请在第一个字段中写一些内容,结果框显示在第二个字段下方。为什么 ul 不引用自己的指令?

【问题讨论】:

    标签: angularjs directive angular-ngmodel


    【解决方案1】:

    发生这种情况是因为您在指令的隔离范围之外定义了搜索功能。要使您的代码正常工作,您需要在范围内定义函数:

    scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) scope.search(newValue) });
    
                    scope.search = function(input) {
                scope.cities = [
              {label: 'Paris'}, 
              {label: 'London'}, 
              {label: 'New York'}, 
              {label: 'Berlin'}, 
              {label: 'Lisbonne'}
            ];
        };
    

    虽然您未能在函数中使用隔离作用域,但它使用调用者可用的最后一个作用域(在您的示例中,您的函数定义被调用两次),因此函数被重新定义两次,第二个定义被从第二个实例的隔离作用域调用在两个调用中都使用了指令。

    【讨论】:

      【解决方案2】:

      将搜索函数的声明移到$watch之前。

      scope.cities = [];
      var search = function(input) {
          scope.cities = [
            {label: 'Paris'}, 
            {label: 'London'}, 
            {label: 'New York'}, 
            {label: 'Berlin'}, 
            {label: 'Lisbonne'}
          ];
      };
      scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) search(newValue)});
      

      JSFiddle

      【讨论】:

        猜你喜欢
        • 2017-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 2018-03-29
        • 2017-06-19
        • 2023-04-03
        • 2021-01-27
        相关资源
        最近更新 更多