将ng模型属性传递给自定义指令

Pass ng-model attribute to custom directive

本文关键字:自定义 指令 ng 模型 属性      更新时间:2023-09-26

因此,我有一个表单,需要在其中使用自定义指令。我需要的是:将user模型传递给指令。

<form>
    <input type="text" ng-model="user.login">
    <input type="password" ng-model="user.password">
    <span ng-custom-directive ng-model="user.testfield"></span>
</form>

指令模板如下:

<span><input type="checkbox" ng-model="[HERE I NEED user.testfield TO WORK WITH user]"> </span>

如何将user模型传递给指令模板?

提交表格后,我需要user.testfield$scope.user中可用,如:

console.log($scope.user)
{
    login: 'test',
    password: 'test',
    testfield: true|false
}

您可以用另一种方法解决plunker

简而言之:

scope: {
    bindedModel: "=ngModel"
},
template: '<input type="text" ng-model="bindedModel">'

好吧,我发现了类似的问题,并以这种方式解决了我的问题:

angular.module("myApp")
  .directive "ngCustomDirective", () ->
      restrict: 'A',
      scope:
        field: '@',
        model: '='
      template: '<span><input type="checkbox" ng-model="model[field]"></span>'

指令用法为:

<span ng-custom-directive
       ng-bind-model="user"
       ng-bind-field="testfield">
</span>