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

How to set ngModel in directive template in Angular?

本文关键字:设置 ngModel 指令 Angular      更新时间:2023-09-26

这是jsfield。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:

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){
})

我创建了一个指令,它可以生成一个带有自定义属性的自定义单选按钮。问题是我不能正确设置ng-model名称,"checked"属性也不能正常工作。
请帮我一把,谢谢!

您使用的简写语法=,这意味着属性名称与您想要绑定到指令范围内的值相同。

如果声明是<div my-rd foo="test">,那么你必须在指令

中指定
model: "=foo" //It tells $compile to bind to the foo attribute.

在你的指令中,你可以访问值

//directive will know only the property inside scope:{'your_propery': value}    
//to access the value inside directive {{your_propery}}
scope.model //{{model}}

在控制器中你可以访问值

$scope.test //{{test }}
详细