[英]How to set ngModel in directive template in Angular?
here is the jsfiddle . 这是jsfiddle 。 HTML: HTML:
<div ng-app="app">
<div ng-controller="ctrl">
<div my-rd name="gender" value="male" model="gender"></div>
<div my-rd name="gender" value="female" model="gender"></div>
<p>Your choice is: {{gender}}</p>
</div>
</div>
JS: JS:
angular.module("app", [])
.directive("myRd", function(){
return{
restrict: "A",
scope: {
name: "@",
value: "@",
model: "="
},
template: "<input name='{{name}}' ng-model='model' value='{{value}}' checked type='radio' />{{value}}"
}
})
.controller("ctrl", function($scope){
})
I created a directive which can generate a custom radio button with custom attributes. 我创建了一个指令,该指令可以生成具有自定义属性的自定义单选按钮。 The problem is I can't set ng-model name correctly and the "checked" property doesn't work as well. 问题是我无法正确设置ng-model名称,“ checked”属性也无法正常工作。
Please give me a hand, many thanks! 请帮帮我,非常感谢!
You use the shorthand syntax =
that means the attribute name is the same as the value you want to bind to inside the directive's scope. 使用简写语法=
表示属性名称与您要在指令范围内绑定的值相同。
If the declaration is <div my-rd foo="test">
then you have to specify in your directive 如果声明为<div my-rd foo="test">
则必须在指令中指定
model: "=foo" //It tells $compile to bind to the foo attribute.
Here in your directive you can access the value 在您的指令中,您可以访问该值
//directive will know only the property inside scope:{'your_propery': value}
//to access the value inside directive {{your_propery}}
scope.model //{{model}}
And in your controller you can access the value 在您的控制器中,您可以访问该值
$scope.test //{{test }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.