简体   繁体   English

AngularJS:将ngModel从控制器传递到指令

[英]AngularJS: passing ngModel from controller to directive

I have a controller with an attribute directive inside it, that directive needs the ngModel of it's controller parent. 我有一个带有属性指令的控制器,该指令需要它的控制器父代的ngModel。

See this Plunkr . 看到这个Plunkr

Problem 问题

Although the form loads correctly, the log inside the directive displays this: 尽管正确加载了表单,但伪指令中的日志显示如下:

a.$…t.aa {$attr: Object, $$element: R[1], fieldValidator: "", boundModel: "person", ngModel: undefined}

Any idea why ngModel is undefined and why boundModel contains the string 'person'? 知道为什么ngModel未定义以及boundModel包含字符串“ person”吗? I've been staring too long at this ... 我一直在盯着这个...

try this 尝试这个

app.directive('fieldValidator', [function(){
  return {
    restrict: 'A',
    scope: {
      boundModel: '='
    },
    controller: function($scope){

    },
    link: function ($scope, $elem, $attrs) {
      console.log($scope.boundModel);
    }
  }
}]);

like other said, there was no ng-model where you use this directive. 就像其他人说的那样,在此指令中没有ng-model。 boundModel: '=' is short for boundModel: '=boundModel' boundModel: '='boundModel: '=boundModel'

And if you want to access boundModel then just use $scope.boundModel ignore what show in $attr guess that not what you need. 如果要访问boundModel,则只需使用$ scope.boundModel忽略$ attr中显示的内容,即可猜测不是您所需要的。

{ boundModel: '=ngModel' } means that you pass boundModel property through ng-model attribute. { boundModel: '=ngModel' }表示您通过ng-model属性传递boundModel属性。 But in a template you don't use ng-model attribute. 但是在模板中,您不使用ng-model属性。 You have bound-model instead. 您有bound-model

scope: {
   boundModel: '=ngModel'
},

You incorrectly use the scope variables. 您错误地使用了范围变量。 When you say '=ngModel', you say that there is an attribute on the directive with the name 'ng-model', which you want to use inside your directive as scope.boundModel. 当您说“ = ngModel”时,您说指令上有一个名为“ ng-model”的属性,您想在指令内将其用作scope.boundModel。

It seems that you want to use ng-model controller, why do you not just use ng-model on your directive instead of boundModel? 看来您想使用ng-model控制器,为什么不只在指令上使用ng-model而不是boundModel?

You could rename the bound-model in you html to ng-model, and remove the scope from the directive. 您可以将html中的bound-model重命名为ng-model,然后从指令中删除作用域。 If you want to use the ngModelController you will need to inject this in the directive link function like this: 如果要使用ngModelController,则需要将其注入指令链接函数中,如下所示:

return {
    restrict: 'A',
    required: '^ngModel',
    scope: {},
    controller: function($scope){

    },
    link: function ($scope, $elem, $attrs, ngModel) {
      console.log($attrs);
    }
  }

With the ngModelController you can then set validity etc. of the person you bind to the ng-model in the html as documented here . 随着ngModelController然后你可以设置绑定到NG-模型的HTML作为记录者的有效性等在这里

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM