Angular指令动态更改select选项

4
我正在尝试编写一个指令,为带有ng-options的中时,项目会消失。
小例子:
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"});
        }
    }

})

jsfidle上。

有什么问题吗?


它不起作用是因为您在指令中隔离了范围。如果您提供更广泛的目标,可能会有所帮助。为什么要在指令中添加项目而不是控制器? - kubuntu
1个回答

1

正如ranru所建议的那样,您可以重写指令,使其不清除select指令的作用域。可以像这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接