简体   繁体   English

Angular动态更改select from指令的选项

[英]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. 我想写一个指令,它为对象添加一个新值,用于选择 ng-options。

But when I add this directive to select , items disapears. 但是当我添加此指令以进行选择时 ,项目会消失。

Small example: 小例子:

html: 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: 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 . jsfidle上

What's wrong? 怎么了?

As ranru suggested, you can rewrite your directive, in such way, that it does not clean the scope of select directive. 正如ranru建议的那样,你可以用这种方式重写你的指令,它不会清除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"});
        }
    }    
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM