我正在尝试将一个对象传递给一个指令,然后该指令可以更新该值。到目前为止,我有以下内容:
<competence-select ng-model="module.selectedCompetence"></competence-select>
指令
angular.module('Competence').directive("competenceSelect", ['competenceService', function (competenceService) {
return {
restrict: "E",
templateUrl: 'js/modules/Competence/directives/competence-select/competence-select.html',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
ngModel.$setViewValue = scope.competenceList;
scope.competences = [];
competenceService.getCompetenceList().then(function (result) {
scope.competences = result;
})
}
};
}]);
(注意要求)
然后是我的指令 html:
<label translate="FORMS.COMPETENCES"></label>
<ui-select multiple reset-search-input="true" ng-model="competenceList" theme="bootstrap"
ng-disabled="disabled">
<ui-select-match placeholder="{{ 'FORMS.COMPETENCES_PLACEHOLDER' | translate }}">{{$item.name}}
<{{$item.competence_type_id == 1 ? 'Faglig' : 'Personlig' }}></ui-select-match>
<ui-select-choices group-by="someGroupFn"
repeat="competence in competences | propsFilter: {name: $select.search, competence_type_id: $select.search}">
<div ng-bind-html="competence.name | highlight: $select.search"></div>
<small>
{{competence.name}}
{{ 'COMPETENCES.TYPE' | translate:{TYPE: competence.competence_type_id} }}
</small>
</ui-select-choices>
</ui-select>
现在我想做的很简单:
ngModel$setViewValue = scope.competence;
设置它应该将 View 中的 ng-model
设置为我在指令中设置的 ng-model。从而将变量“向上”解析为指令的声明:
<competence-select ng-model="module.selectedCompetence"></competence-select>
遗憾的是,情况并非如此。
谁能告诉我我做错了什么?
最佳答案
在您的指令中进行这些更改
angular.module('Competence').directive("competenceSelect", ['competenceService', function (competenceService) {
return {
restrict: "E",
templateUrl: 'js/modules/Competence/directives/competence-select/competence-select.html',
require: 'ngModel',
scope:{ ngModel : "=" },
link: function (scope, element, attr, ngModel) {
ngModel.$setViewValue = scope.competenceList;
scope.competences = [];
competenceService.getCompetenceList().then(function (result) {
scope.competences = result;
scope.ngModel = scope.competences;
})
}
};
}]);
关于javascript - 带有指令的 Angular ngModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37002479/