AngularJS指令数据正在被覆盖

AngularJS directive data is being overwritten

本文关键字:覆盖 指令 数据 AngularJS      更新时间:2024-05-25

我制作了自己的type-ahead指令,该指令会自动填充一些名称。我的页面前面有两种不同的语气,都是相同的类型。其中一个需要得到每个名字,而另一个只需要得到一些名字。哪一个前面的类型最后被加载,重写第一个前面类型的数据。所以,如果我加载一个应该先得到一些名字的,然后加载一个得到所有名字的。他们两个都抢了所有的名字。

如有任何帮助,我们将不胜感激。

这是我的指示:

templates.directive("referralTypeAhead", function (Referrals,AlertFactory) {
return {
restrict:"EA",
replace: true,
require:'ngModel',
// scope: {everyone: "@"},
template: '<input type="text" typeahead="patient.id as patient.plast + '', '' + patient.pfirst + '' '' + patient.mi for patient in patients | filter:$viewValue | limitTo:8" typeahead-min-length="3" typeahead-editable="false" typeahead-input-formatter="formatLabel($model)" class="form-control" />',
link: function(scope, element, attrs, ngModel) {
        var every = attrs.everyone ? attrs.everyone : "false";
        if (everyone === "false") {
          Referrals.getSomeNames({everyone:every}).$promise.then(function(result) {
            var patients = result;
            for (var i = 0; i < patients.length; ++i) {
              if (!patients[i]['mi']) {
                patients[i]['mi'] = '';
              }
            }
            scope.patients = patients;
          },function(result) {
            AlertFactory.addAlert('warning','ERROR: Unable to load data for the referral-type-ahead');
          });
        }
        else {
          Referrals.getAllNames({everyone:every}).$promise.then(function(result) {
            var patients = result;
            for (var i = 0; i < patients.length; ++i) {
              if (!patients[i]['mi']) {
                patients[i]['mi'] = '';
              }
            }
            scope.patients = patients;
          },function(result) {
            AlertFactory.addAlert('warning','ERROR: Unable to load data for the referral-type-ahead');
          });
        }
        scope.formatLabel = function(model) {
          if (scope.patients) {
            for (var i = 0; i < scope.patients.length; ++i) {
              if (scope.patients[i].id == model) {
                return scope.patients[i].plast + ', ' + scope.patients[i].pfirst + ' ' + scope.patients[i].mi;
              }
            }
          }
        };
     }
   };
});

这是我的html:

<referral-type-ahead everyone="false" ng-model="patient.id"></referral-type-ahead>
<referral-type-ahead everyone='true' ng-model="patient.id"></referral-type-ahead>

我不明白为什么第二组数据会覆盖第一组数据。

创建可重复使用的组件/小部件/指令时,请创建isolateScope。

在指令定义中声明scope: {}

它每次使用该指令都会创建私有的、非共享的作用域。

更多关于isolateScope的信息,请参阅angular文档

顾名思义,指令的隔离范围隔离除了已显式添加到作用域的模型之外的所有内容:{}hash对象。这在构建可重用组件时很有帮助,因为它阻止组件更改模型状态,但您明确传入的模型。

注意:通常情况下,作用域原型继承自其父作用域。一孤立作用域没有。参见"指令定义对象-范围"有关隔离作用域的更多信息,请参阅。

最佳实践:当制作要在整个应用程序中重复使用的组件。