【问题标题】:AngularJS - Create a directive that uses ng-modelAngularJS - 创建一个使用 ng-model 的指令
【发布时间】:2012-12-16 10:41:23
【问题描述】:

我正在尝试创建一个指令,该指令将创建一个与创建指令的元素具有相同 ng-model 的输入字段。

这是我到目前为止的想法:

HTML

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  This scope value <input ng-model="name">
  <my-directive ng-model="name"></my-directive>
</body>
</html>

JavaScript

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = "Felipe";
});

app.directive('myDirective', function($compile) {
  return {
    restrict: 'E',
    scope: {
      ngModel: '='
    },
    template: '<div class="some"><label for="{{id}}">{{label}}</label>' +
      '<input id="{{id}}" ng-model="value"></div>',
    replace: true,
    require: 'ngModel',
    link: function($scope, elem, attr, ctrl) {
      $scope.label = attr.ngModel;
      $scope.id = attr.ngModel;
      console.debug(attr.ngModel);
      console.debug($scope.$parent.$eval(attr.ngModel));
      var textField = $('input', elem).
        attr('ng-model', attr.ngModel).
        val($scope.$parent.$eval(attr.ngModel));

      $compile(textField)($scope.$parent);
    }
  };
});

但是,我不确定这是处理这种情况的正确方法,并且存在一个错误,即我的控件没有使用 ng-model 目标字段的值进行初始化。

这是上面代码的 Plunker:http://plnkr.co/edit/IvrDbJ

处理这个问题的正确方法是什么?

编辑:从模板中删除ng-model="value" 后,这似乎工作正常。但是,我会保持这个问题的开放性,因为我想仔细检查这是正确的做法。

【问题讨论】:

  • 如果删除scope 并将其设置为scope: false 会怎样?在这种情况下如何绑定到ng-model

标签: angularjs directive


【解决方案1】:

这是一个有点晚的答案,但我发现这个很棒的post 关于NgModelController,我认为这正是您想要的。

TL;DR - 您可以使用require: 'ngModel',然后将NgModelController 添加到您的链接函数中:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}

这样一来,无需任何技巧 - 您使用的是 Angular 的内置 ng-model

【讨论】:

    【解决方案2】:

    编辑:这个答案很旧,可能已经过时了。只是一个提醒,所以它不会让人们误入歧途。我不再使用 Angular,所以我无法进行改进。


    这实际上是一个很好的逻辑,但你可以稍微简化一下。

    指令

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.model = { name: 'World' };
      $scope.name = "Felipe";
    });
    
    app.directive('myDirective', function($compile) {
      return {
        restrict: 'AE', //attribute or element
        scope: {
          myDirectiveVar: '=',
         //bindAttr: '='
        },
        template: '<div class="some">' +
          '<input ng-model="myDirectiveVar"></div>',
        replace: true,
        //require: 'ngModel',
        link: function($scope, elem, attr, ctrl) {
          console.debug($scope);
          //var textField = $('input', elem).attr('ng-model', 'myDirectiveVar');
          // $compile(textField)($scope.$parent);
        }
      };
    });
    

    带有指令的 HTML

    <body ng-controller="MainCtrl">
      This scope value <input ng-model="name">
      <my-directive my-directive-var="name"></my-directive>
    </body>
    

    CSS

    .some {
      border: 1px solid #cacaca;
      padding: 10px;
    }
    

    您可以通过Plunker 看到它的实际效果。

    这是我看到的:

    • 我理解您为什么要使用“ng-model”,但在您的情况下没有必要。 ng-model 是将 existing html 元素与范围内的值链接。由于您自己创建了一个指令,因此您正在创建一个“新”html 元素,因此您不需要 ng-model。

    编辑 正如 Mark 在他的评论中所提到的,您没有理由不能使用 ng-model,只是为了遵守惯例。

    • 通过在指令中显式创建一个作用域(“隔离”作用域),该指令的作用域无法访问父作用域上的“名称”变量(我认为这就是您想要使用 ng-model 的原因)。
    • 我从您的指令中删除了 ngModel 并将其替换为自定义名称,您可以将其更改为任何名称。
    • 使这一切仍然有效的原因是作用域中的“=”符号。查看“范围”标题下的文档docs

    通常,如果您希望指令中的值始终映射到父范围中的值,则您的指令应使用隔离范围(您正确地做到了)并使用“=”类型范围。

    【讨论】:

    • +1,但我不确定我是否同意“ng-model 是将现有 HTML 元素与范围内的值链接”的说法。 Angular 文档中的两个 contenteditable 指令示例——forms pageNgModelController page——都使用 ng-model。并且 ngModelController 页面说这个控制器“旨在通过其他指令进行扩展”。
    • 我不确定为什么这个答案的评价如此之高,因为它没有完成最初的问题——即使用 ngModel。是的,可以通过将状态放在父控制器中来避免使用 ngModel,但这是以两个控制器紧密绑定并且无法独立使用/重用它们为代价的。这就像使用全局变量而不是在两个组件之间设置监听器一样——从技术上讲它可能更简单,但在大多数情况下它并不是一个好的解决方案。
    • 我要补充一点,如果他想依赖父控制器,无论如何他都应该用 'require: ^parent' 注入它——这样他就可以在需要时使依赖项显式和可选。跨度>
    • @Jeroen 我认为它的主要好处是与模型作为hg-model 传入的其他地方的一致性(而不是耦合问题,IMO)。这样,无论是&lt;input&gt; 还是自定义指令,数据上下文始终使用 ng-model,从而简化了 HTML 编写器的认知开销。 IE。它使 HTML 编写者不必找出每个指令的 my-directive-var 的名称是什么,特别是因为没有自动完成功能可以帮助您。
    • 嗯...好的...但是现在这不再适用于 ng-model-options 或任何其他 ng 模型的东西,是吗?
    【解决方案3】:

    创建隔离范围是不可取的。我会避免使用范围属性并做这样的事情。 scope:true 为您提供了一个新的子范围,但不是孤立的。然后使用 parse 将局部范围变量指向用户提供给 ngModel 属性的同一对象。

    app.directive('myDir', ['$parse', function ($parse) {
        return {
            restrict: 'EA',
            scope: true,
            link: function (scope, elem, attrs) {
                if(!attrs.ngModel) {return;}
                var model = $parse(attrs.ngModel);
                scope.model = model(scope);
            }
        };
    }]);
    

    【讨论】:

      【解决方案4】:

      从 Angular 1.5 开始,可以使用组件。组件很容易解决这个问题。

      <myComponent data-ng-model="$ctrl.result"></myComponent>
      
      app.component("myComponent", {
          templateUrl: "yourTemplate.html",
          controller: YourController,
          bindings: {
              ngModel: "="
          }
      });
      

      在 YourController 中你需要做的就是:

      this.ngModel = "x"; //$scope.$apply("$ctrl.ngModel"); if needed
      

      【讨论】:

      • 我发现,如果您确实使用“=”而不是“
      • @MarcStober 在“YourController 内部”中,我只想说明 ngModel 可用作 getter 和 setter。在本例中,$ctrl.result 将变为“x”。
      • 好的。我认为重要的另一部分是您还可以在控制器模板中执行input ng-model="$ctrl.ngModel",它也会与 $ctrl.result 同步。
      【解决方案5】:

      我综合了所有答案,现在有两种方法可以使用 ng-model 属性:

      • 具有复制 ngModel 的新范围
      • 具有在链接上进行编译的相同范围

      var app = angular.module('model', []);
      
      app.controller('MainCtrl', function($scope) {
        $scope.name = "Felipe";
        $scope.label = "The Label";
      });
      
      app.directive('myDirectiveWithScope', function() {
        return {
          restrict: 'E',
          scope: {
            ngModel: '=',
          },
          // Notice how label isn't copied
          template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',
          replace: true
        };
      });
      app.directive('myDirectiveWithChildScope', function($compile) {
        return {
          restrict: 'E',
          scope: true,
          // Notice how label is visible in the scope
          template: '<div class="some"><label>{{label}}: <input></label></div>',
          replace: true,
          link: function ($scope, element) {
            // element will be the div which gets the ng-model on the original directive
            var model = element.attr('ng-model');
            $('input',element).attr('ng-model', model);
            return $compile(element)($scope);
          }
        };
      });
      app.directive('myDirectiveWithoutScope', function($compile) {
        return {
          restrict: 'E',
          template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',
          replace: true,
          link: function ($scope, element) {
            // element will be the div which gets the ng-model on the original directive
            var model = element.attr('ng-model');
            return $compile($('input',element).attr('ng-model', model))($scope);
          }
        };
      });
      app.directive('myReplacedDirectiveIsolate', function($compile) {
        return {
          restrict: 'E',
          scope: {},
          template: '<input class="some">',
          replace: true
        };
      });
      app.directive('myReplacedDirectiveChild', function($compile) {
        return {
          restrict: 'E',
          scope: true,
          template: '<input class="some">',
          replace: true
        };
      });
      app.directive('myReplacedDirective', function($compile) {
        return {
          restrict: 'E',
          template: '<input class="some">',
          replace: true
        };
      });
      .some {
        border: 1px solid #cacaca;
        padding: 10px;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
      <div ng-app="model" ng-controller="MainCtrl">
        This scope value <input ng-model="name">, label: "{{label}}"
        <ul>
          <li>With new isolate scope (label from parent):
            <my-directive-with-scope ng-model="name"></my-directive-with-scope>
          </li>
          <li>With new child scope:
            <my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>
          </li>
          <li>Same scope:
            <my-directive-without-scope ng-model="name"></my-directive-without-scope>
          </li>
          <li>Replaced element, isolate scope:
            <my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>
          </li>
          <li>Replaced element, child scope:
            <my-replaced-directive-child ng-model="name"></my-replaced-directive-child>
          </li>
          <li>Replaced element, same scope:
            <my-replaced-directive ng-model="name"></my-replaced-directive>
          </li>
        </ul>
        <p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope.
        <p>Also notice how removing jQuery makes it so only the new-isolate-scope version works.
        <p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0
      </div>

      我不确定我是否喜欢在链接时进行编译。但是,如果您只是将元素替换为另一个元素,则无需这样做。

      总而言之,我更喜欢第一个。只需将范围设置为 {ngModel:"="} 并将 ng-model="ngModel" 设置为模板中所需的位置即可。

      更新:我内联了代码 sn-p 并为 Angular v1.2 更新了它。事实证明,隔离范围仍然是最好的,尤其是在不使用 jQuery 时。所以归结为:

      • 您是否要替换单个元素:只需替换它,不要管范围,但请注意,对于 v2.0,replace 已弃用:

        app.directive('myReplacedDirective', function($compile) {
          return {
            restrict: 'E',
            template: '<input class="some">',
            replace: true
          };
        });
        
      • 否则使用这个:

        app.directive('myDirectiveWithScope', function() {
          return {
            restrict: 'E',
            scope: {
              ngModel: '=',
            },
            template: '<div class="some"><input ng-model="ngModel"></div>'
          };
        });
        

      【讨论】:

      • 我用所有三种范围可能性以及模板的子元素或模板的根元素更新了 plunker。
      • 这很好,但是您如何从本质上使它成为可选的呢?我正在为 UI 库创建一个文本框指令,并且我希望模型是可选的,这意味着如果未设置 ngModel,文本框仍然可以工作。
      • @NickRadford 只需检查是否在 $scope 上定义了 ngModel,如果没有,不要使用它?
      • 在隔离范围内重用ng-model 会有任何问题或额外开销吗?
      • @jeffling 不确定,但我不这么认为。复制 ngModel 的重量很轻,而且孤立的范围限制了曝光。
      【解决方案6】:

      没那么复杂: 在您的指令中,使用别名:scope:{alias:'=ngModel'}

      .directive('dateselect', function () {
      return {
          restrict: 'E',
          transclude: true,
          scope:{
              bindModel:'=ngModel'
          },
          template:'<input ng-model="bindModel"/>'
      }
      

      在您的 html 中,正常使用

      <dateselect ng-model="birthday"></dateselect>
      

      【讨论】:

      • 这在处理像 Kendo UI 这样的库时要容易得多。谢谢!
      【解决方案7】:

      只有在需要访问模型的 $viewValue 或 $modelValue 时才需要 ng-model。见NgModelController。在这种情况下,您将使用require: '^ngModel'

      其他的请看Roys answer

      【讨论】:

      • ng-model 也很有用,即使您不需要 $viewValue 或 $modelValue。即使您只想要 ng-model 的数据绑定功能,它也很有用,例如 @kolrie 的示例。
      • 只有当 ng-model 应用于父元素时,^ 才应该存在
      【解决方案8】:

      我不会通过属性设置 ngmodel,你可以在模板中指定它:

      template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',
      

      plunkerhttp://plnkr.co/edit/9vtmnw?p=preview

      【讨论】:

        猜你喜欢
        • 2016-04-20
        • 2015-05-05
        • 2012-10-23
        • 1970-01-01
        • 2016-03-07
        • 1970-01-01
        • 2014-02-14
        • 2015-10-13
        • 1970-01-01
        相关资源
        最近更新 更多