Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngModel with directive

I am trying to pass down an object into a directive that can then update this value. so far i have the following:

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

Directive

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

(Notice the require)

And then my directive 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>

Now what i want to do is fairly simple:

ngModel$setViewValue = scope.competence;

Setting this should set the ng-model in the view to be the ng-model i set on the directive. Thereby parsing the variable "up" to the declarating of the directive:

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

Sadly this is not the case.

Can anyone tell me what ive done wrong?

like image 676
Marc Rasmussen Avatar asked Dec 12 '25 21:12

Marc Rasmussen


1 Answers

Make these changes in your directive

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;
            })
        }
    };
}]);
like image 99
byteC0de Avatar answered Dec 15 '25 11:12

byteC0de