Ihor Shubin
Ihor Shubin

Reputation: 10726

Angular dynamically change options for select from directive

I'm tring to write directive which adds a new value to object for select with ng-options.

But when I add this directive to select, items disapears.

Small example:

html:

<div ng:app="editor" ng:controller="BaseController">
    <select ng-model='m' ng-options='i.Id as i.Val for i in model.items' add-new-val='model.items'></select>
    <select ng-model='m' ng-options='i.Id as i.Val for i in model.items'></select>
</div>

javascript:

var module = angular.module('editor', []);

function BaseController($scope){
    $scope.model = {
        items: [{Id:1, Val:"_1"}]
    }

    $scope.m = 1;
}

module.directive('addNewVal',function(){
    return {
        scope:{
            items: '=addNewVal'
        },
        controller: function($scope){
            $scope.items.push({Id: 3, Val: "Have a nice day"});
        }
    }

})

On jsfidle.

What's wrong?

Upvotes: 4

Views: 903

Answers (1)

gor
gor

Reputation: 11658

As ranru suggested, you can rewrite your directive, in such way, that it does not clean the scope of select directive. Something like this:

module.directive('addNewVal',function(){
    return {
        controller: function($attrs, $scope){         
            var data = $scope.$eval($attrs.addNewVal);
            data.push({Id: 3, Val: "Have a nice day"});
        }
    }    
})

Upvotes: 1

Related Questions