AngularJS中的可重用指令

Reusable directive in AngularJS

本文关键字:指令 AngularJS      更新时间:2023-09-26

我有一个指令,当在输入中检测到更改时需要一个事件,我想用相同的指令创建许多输入。

例如:

  <body ng-controller="MainCtrl">
    <input ng-model='val'  caret="2"><br/>
    <input ng-model'"val2' caret="2"><br/>
    <input ng-model'"val3' caret="2"><br/>
    <input ng-model'"val4' caret="2"><br/>
     ....
    <input ng-model'"valn' caret="2"><br/>
  </body>

问题是作用域的第一个参数。$watch是模型名。我怎样才能使范围。

改变这一行

scope.$watch('val', function(newValue, oldValue) {

scope.$watch(attrs.ngModel, function(newValue, oldValue) {

就可以了。为ng-model设置属性值

查看我的plunkr http://plnkr.co/edit/U8An4LJwzneZWv2nUNCT?p=preview