带有指令的Angular ngModel

时间:2016-05-03 11:09:23

标签: javascript angularjs

我试图将一个对象传递给一个指令,然后可以更新这个值。到目前为止,我有以下内容:

 <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}}
        &lt;{{$item.competence_type_id == 1 ? 'Faglig' : 'Personlig' }}&gt;</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;

设置此项应将视图中的ng-model设置为我在指令上设置的ng-model。从而将变量“up”解析为声明指令:

<competence-select ng-model="module.selectedCompetence"></competence-select>

可悲的是,事实并非如此。

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

在指令中进行这些更改

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;
            })
        }
    };
}]);