我已经制作了自己的预输入指令,它会自动填充一些名称。我的页面上有两种不同模式的相同预输入内容。其中一个需要获取所有名称,而另一个只需要获取部分名称。最后加载的任何一个预输入都会覆盖第一个预输入的数据。因此,如果我加载应该首先获取一些名称的那个,然后加载应该获取所有名称的那个。他们俩都抢到了所有名字。
任何帮助将不胜感激。
这是我的指令:
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。
在指令定义中声明范围:{}
它会根据该指令的使用创建私有(private)的、非共享的范围。
有关 Angular 文档中的isolateScope 的更多信息。
As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in.
Note: Normally, a scope prototypically inherits from its parent. An isolated scope does not. See the "Directive Definition Object - scope" section for more information about isolate scopes.
Best Practice: Use the scope option to create isolate scopes when making components that you want to reuse throughout your app.
关于javascript - AngularJS 指令数据被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28724945/