AngularJS - 创建使用ng-model的指令

kol*_*rie 293 directive angularjs

我正在尝试创建一个指令,该指令将使用与创建指令的元素相同的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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Roy*_*ove 209

编辑:这个答案很旧,可能已经过时了.只是抬头,所以它不会让人误入歧途.我不再使用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);
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

带指令的Html

<body ng-controller="MainCtrl">
  This scope value <input ng-model="name">
  <my-directive my-directive-var="name"></my-directive>
</body>
Run Code Online (Sandbox Code Playgroud)

CSS

.some {
  border: 1px solid #cacaca;
  padding: 10px;
}
Run Code Online (Sandbox Code Playgroud)

你可以通过这个Plunker看到它的实际效果.

这是我看到的:

  • 我理解你为什么要使用'ng-model',但在你的情况下它没有必要.ng-model用于链接现有 html元素和范围中的值.由于您自己创建了一个指令,因此您正在创建一个"新的"html元素,因此您不需要ng-model.

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

  • 通过在指令中显式创建范围("隔离"范围),指令的范围无法访问父范围上的"name"变量(这就是为什么我想要使用ng-model).
  • 我从您的指令中删除了ngModel,并将其替换为您可以更改为任何内容的自定义名称.
  • 使一切仍然有用的事情是'='在范围内签名.查看"范围"标题下的文档 文档.

通常,如果希望指令中的值始终映射到父作用域中的值,则指令应使用隔离作用域(您已正确执行)并使用'='类型作用域.

  • 我不确定为什么这个答案得到如此高的评价,因为它没有完成原始问题的要求 - 即使用ngModel.是的,可以通过在父控制器中放置状态来避免使用ngModel,但这是以两个控制器紧密绑定而不能独立使用/重用它为代价的.这就像使用全局变量而不是在两个组件之间设置一个监听器 - 它在技术上可能更简单,但在大多数情况下它不是一个好的解决方案. (33认同)
  • +1,但我不确定我是否同意"ng-model是将现有HTML元素与范围中的值相关联"的说法.在角文档的两个`contenteditable`指令实例 - [形成页](http://docs.angularjs.org/guide/forms),[NgModelController页](http://docs.angularjs.org/api/ ng.directive:ngModel.NgModelController) - 都使用ng-model.并且ngModelController页面表明该控制器"意图由其他指令扩展". (18认同)
  • @Jeroen我认为它的主要好处是与模型作为`hg-model`传递的其他地方的一致性(而不是耦合问题,IMO).这样,数据上下文总是使用ng-model,无论它是`<input>`还是自定义指令,从而简化了HTML编写器的认知开销.也就是说,它保存了HTML编写器必须找出每个指令的"my-directive-var"的名称,特别是因为没有自动完成功能可以帮助你. (3认同)
  • @Mark - 你是对的,我已经编辑了一下这个答案. (2认同)
  • 嗯...好吧......但现在这不再适用于`ng-model-options`或任何其他ng型号的东西,是吗? (2认同)

w00*_*00t 67

我对所有答案进行了组合,现在有两种方法可以使用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
  };
});
Run Code Online (Sandbox Code Playgroud)
.some {
  border: 1px solid #cacaca;
  padding: 10px;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

我不确定我喜欢链接时的编译.但是,如果您只是将元素替换为另一个元素,则不需要这样做.

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

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

  • 您是否正在替换单个元素:只需替换它,保留范围,但请注意,对于v2.0,不推荐使用replace:

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

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

  • @jeffling不确定,但我不这么认为.复制ngModel非常轻,并且隔离范围限制了曝光. (2认同)

AiS*_*ang 52

它不是那么复杂:在你的dirctive中,使用别名: scope:{alias:'=ngModel'}

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

在您的HTML中,正常使用

<dateselect ng-model="birthday"></dateselect>
Run Code Online (Sandbox Code Playgroud)


asg*_*oth 30

当您需要访问模型的$ viewValue或$ modelValue时,您只需要ng-model.请参阅NgModelController.在那种情况下,你会使用require: '^ngModel'.

其余的,请参阅Roys的回答.

  • 即使您不需要$ viewValue或$ modelValue,ng-model也很有用.即使你只想要ng-model的数据绑定功能,它也很有用,比如@ kolrie的例子. (2认同)

Yan*_*aim 18

这是一个有点晚了答案,但我发现这个真棒职位有关NgModelController,我认为这正是您要寻找的.

TL; DR - 您可以使用require: 'ngModel'然后添加NgModelController到您的链接功能:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}
Run Code Online (Sandbox Code Playgroud)

这样就不需要hacks - 你正在使用Angular的内置功能 ng-model