简体   繁体   English

如何在Angular的指令模板中设置ngModel?

[英]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 }}

More details 更多细节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 5 Reactive Forms:没有将“exportAs”设置为“ngModel”的指令 - Angular 5 Reactive Forms : There is no directive with "exportAs" set to "ngModel" Angular 2+ 错误 - 未捕获的错误:模板解析错误:没有将“exportAs”设置为“ngModel”(“-group”&gt;)的指令 - Angular 2+ Error - Uncaught Error: Template parse errors: There is no directive with "exportAs" set to "ngModel" ("-group"> 带有指令的Angular ngModel - Angular ngModel with directive 带有ngModel的角度递归指令 - Angular Recursive Directive with ngModel Angular 2 ngModel mutator 指令 - Angular 2 ngModel mutator directive Angular 2错误 - 没有指令将“exportAs”设置为RC4版本的“ngModel” - Angular 2 error- There is no directive with “exportAs” set to “ngModel” with RC4 version 避免对ngModel [Angular]进行writeOut的指令 - Directive to avoid writeOut to ngModel [Angular] 角度指令ngModel在模糊时更改 - angular directive ngModel change on blur 带有隔离范围的指令中的表单输入:如何将ngModel设置为正确的范围? - Form input in a directive with isolated scope: How to set ngModel to the correct scope? Angular.js-在指令中设置ng-pattern时ngModel值未定义 - Angular.js - ngModel value is undefined when ng-pattern is set in directive
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM