我试图创建一个指令,将创建一个输入字段与元素相同的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"后,这似乎工作得很好。但是,我将保留这个问题,因为我想再次确认这是正确的方法。


当前回答

我取了所有答案的组合,现在有两种方法来使用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>

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

总之,我更喜欢第一个。只需将scope设置为{ngModel:"="},并在模板中需要的位置设置ng-model="ngModel"。

更新:我内联了代码片段,并为Angular v1.2更新了它。事实证明,隔离作用域仍然是最好的,特别是在不使用jQuery的情况下。所以可以归结为:

替换单个元素:只需替换它,保持作用域不变,但注意replace在2.0版本中已弃用: app.directive('myReplacedDirective', function($compile) { 返回{ 限制:“E”, '<input class="some">', 替换:真 }; }); 否则使用这个: app.directive('myDirectiveWithScope', function() { 返回{ 限制:“E”, 范围:{ ngModel:“=”, }, template: '<div class="some"><input ng-model="ngModel"></div>' }; });

其他回答

从Angular 1.5开始,就可以使用组件了。组件是很容易解决这个问题的方法。

<myComponent data-ng-model="$ctrl.result"></myComponent>

app.component("myComponent", {
    templateUrl: "yourTemplate.html",
    controller: YourController,
    bindings: {
        ngModel: "="
    }
});

在你的控制器中,你需要做的是:

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

当你需要访问模型的$viewValue或$modelValue时,你只需要ng-model。看到NgModelController。在这种情况下,你会使用require: '^ngModel'。

至于其他,请参见罗伊的回答。

创建隔离作用域是不可取的。我将避免使用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);
        }
    };
}]);

这是一个有点晚的回答,但我发现了一篇关于NgModelController的很棒的文章,我认为这正是你正在寻找的。

你可以使用require: 'ngModel',然后将NgModelController添加到你的链接函数中:

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

这样,你就不需要任何技巧了——你使用的是Angular内置的ng-模型

我取了所有答案的组合,现在有两种方法来使用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>

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

总之,我更喜欢第一个。只需将scope设置为{ngModel:"="},并在模板中需要的位置设置ng-model="ngModel"。

更新:我内联了代码片段,并为Angular v1.2更新了它。事实证明,隔离作用域仍然是最好的,特别是在不使用jQuery的情况下。所以可以归结为:

替换单个元素:只需替换它,保持作用域不变,但注意replace在2.0版本中已弃用: app.directive('myReplacedDirective', function($compile) { 返回{ 限制:“E”, '<input class="some">', 替换:真 }; }); 否则使用这个: app.directive('myDirectiveWithScope', function() { 返回{ 限制:“E”, 范围:{ ngModel:“=”, }, template: '<div class="some"><input ng-model="ngModel"></div>' }; });