Angular dynamically change options for selection from directive

I am trying to write a directive that adds a new value to an object for select using ng-options.

But when I add this directive to select , the elements will disappear.

A 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"});
        }
    }

})

In jsfidle .

What's wrong?

+4
source share
1 answer

As ranru, you can rewrite your directive so that it does not clear the scope of select ., 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"});
        }
    }    
})
+1
source

All Articles