带有动态表达式的 ng-options 不起作用 [英] ng-options with a dynamic expression is not working
问题描述
我正在尝试以 angular 创建一个 directive
,以替换常规下拉列表.我需要能够将动态表达式设置为 ng-options
但似乎在指令中不起作用.
I'm trying to create a directive
in angular, to replace the regular dropdown. I need to be able to set a dynamic expression to ng-options
but doesn't seem to be working inside the directive.
它在外面完美运行.
这是指令
angular.module('app.dropdown',[])
.directive('swDropdown',[ function ( ){
return {
restrict: 'E',
replace: true,
template:'<div><select ng-model="swModel" ng-options="{{expression}}" ></div>',
link: link,
scope:{
swOptions:"=",
swLabel:'@',
swValue:'@',
swModel:"="
}
};
function link (scope, element, attrs) {
scope.defaultText = angular.isDefined(attrs.swDefaultText)?attrs.swDefaultText:'Choose';
scope.selected = scope.defaultText;
scope.expression = 'item as item.name for item in swOptions';
}
}]);
控制器示例:
angular.module('app',['app.dropdown']).controller('Ctrl', function($scope){
$scope.model="";
$scope.expression = 'item as item.name for item in options';
$scope.options = [
{id:1,name:'hola'},
{id:2,name:'chau'}]
});
HTML:
<body ng-app="app" ng-controller="Ctrl">
<h1>Hello Plunker!</h1>
Working dropdown<br/>
<select ng-model="model" ng-options="{{expression}}"></select>
<br/>
Not working inside a directive
<sw-dropdown sw-model="model" sw-options="options"></sw-dropdown>
</body>
关于为什么它不起作用的任何线索?
Any clue about why it is not working?
谢谢!
推荐答案
这是个好问题.归根结底,当 被 Angular 处理时,
ng-options
需要有一个值.
This is a good question. At the end of the day, ng-options
needs to have a value when <select>
is being processed by Angular.
1) 您可以在预链接"功能中进行设置:
1) You can either set it up in the "pre-link" function:
.directive('swDropdown',[function (){
return {
...
link: {
pre: function(scope){
scope.expression = "item as item.name for item in swOptions";
},
post: // your normal link function
}
}
}]);
2) 或者,如果你很懒,你可以将 ng-if="expression"
添加到模板中,并保持一切不变:
2) Or, if you are lazy, you could just add ng-if="expression"
to the template, and keep everything the same:
.directive('swDropdown',[function (){
return {
...
template: '<div><select ng-if="expression" ng-model="swModel" ng-options="{{expression}}"></select></div>',
link: link // this is treated as post-link
}
function link(scope, element){
// ...
}
}]);
3) 如果您的表达式确实需要可变和可修改(看起来很奇怪,应该使用更合适的 ViewModel 解决),那么您需要强制重新编译:
3) if your expression is truly needs to be mutable and modifyable (seems like a weird case and should probably be address with a more suitable ViewModel), then you'd need to force re-compilation:
function link(scope, element){
...
scope.changeExpression = function(newExpression){
scope.expression = newExpression;
// $compile should be injected into your directive's function
$compile(element)(scope);
}
}
顺便说一句,只需将 $compile(element)(scope);
添加到您当前的链接函数中即可.
Btw, just adding $compile(element)(scope);
to your current link function would do the trick.
这篇关于带有动态表达式的 ng-options 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!