vcu*_*gvu 5 javascript angularjs angular-ngmodel
我正在尝试使用Angular指令创建自定义选择元素.
该指令中的模板包含一个select元素,该元素具有我想从自定义元素获取的ng-model属性.
<custom-select inner-model="modelName">
<select model="{{model}}"></select>
</custom-select>
Run Code Online (Sandbox Code Playgroud)
我的问题是Angular不允许将Angular表达式作为ng-model属性的值.
我也试过设置一个属性
link: function(scope, element, attributes) {
element[0].childNodes[0].setAttribute('data-ng-model', attributes.innerModel);
}
Run Code Online (Sandbox Code Playgroud)
它确实采用了具有正确值的属性,但它仍然无效.
这是我的傻瓜:Plunker
您需要定义一个隔离的范围。这实际上会将分配给 attribute 的外部范围属性绑定inner-model到内部范围属性innerModel,然后您可以在模板中使用它。
app.directive('customSelect', function() {
return {
restrict: 'E',
transclude: true,
scope: {
innerModel: "="
}
template: '<select ng-model="innerModel" data-ng-transclude></select>',
};
});
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
<custom-select inner-model="someScopeProperty">
<option value="1">One</option>
<option value="2">Two</option>
...
</custom-select>
Run Code Online (Sandbox Code Playgroud)
(尽管,我仍然对你想要实现的目标感到困惑)