[英]Angular Expression in ng-model
I'm trying to create a custom select element with an Angular directive. 我正在尝试使用Angular指令创建自定义选择元素。
The template in this directive contains a select element with a ng-model attribute that I want to get from the custom element. 该指令中的模板包含一个select元素,该元素具有我想从自定义元素获取的ng-model属性。
<custom-select inner-model="modelName">
<select model="{{model}}"></select>
</custom-select>
My problem is Angular doesn't allow an Angular expression as a value for the ng-model attribute. 我的问题是Angular不允许将Angular表达式作为ng-model属性的值。
I also tried to set an attribute with 我也试过设置一个属性
link: function(scope, element, attributes) {
element[0].childNodes[0].setAttribute('data-ng-model', attributes.innerModel);
}
It does take the attribute with the right value but it is still not working. 它确实采用了具有正确值的属性,但它仍然无效。
You need to define an isolated scope. 您需要定义一个隔离的范围。 This will essentially bind the outer scope property assigned to
inner-model
attribute to internal scope property innerModel
, which you could then use in your template. 这将基本上将分配给
inner-model
属性的外部作用域属性绑定到内部作用域属性innerModel
,然后可以在模板中使用该属性。
app.directive('customSelect', function() {
return {
restrict: 'E',
transclude: true,
scope: {
innerModel: "="
}
template: '<select ng-model="innerModel" data-ng-transclude></select>',
};
});
Then you could do: 然后你可以这样做:
<custom-select inner-model="someScopeProperty">
<option value="1">One</option>
<option value="2">Two</option>
...
</custom-select>
(Although, I'm still puzzled by what you are trying to achieve) (虽然,我仍然对你想要达到的目标感到困惑)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.