首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >AngularJS -创建使用ng-model的指令

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

Stack Overflow用户
提问于 2013-01-02 08:44:52
回答 8查看 269.7K关注 0票数 297

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

这是我到目前为止想出来的:

HTML

代码语言:javascript
复制
<!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

代码语言: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目标字段的值进行初始化。

下面是上面代码的一部分:http://plnkr.co/edit/IvrDbJ

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

编辑:从模板中删除ng-model="value"之后,似乎工作得很好。但是,我将保留这个问题,因为我想仔细检查这是不是正确的方法。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2013-01-02 11:18:15

:这个答案是旧的,可能已经过时了。只是提醒一下,这样就不会误入歧途。我不再使用Angular,所以我不是一个很好的改进位置。

这实际上是一个很好的逻辑,但是你可以把事情简化一点。

指令

代码语言:javascript
复制
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

代码语言:javascript
复制
<body ng-controller="MainCtrl">
  This scope value <input ng-model="name">
  <my-directive my-directive-var="name"></my-directive>
</body>

CSS

代码语言:javascript
复制
.some {
  border: 1px solid #cacaca;
  padding: 10px;
}

您可以使用此Plunker查看它的实际效果。

这是我所看到的:

  • 我理解你为什么要使用'ng-model‘,但在你的例子中,它不是必须的。ng-model是将现有的html元素与作用域中的值链接起来。由于您自己创建了一个指令,因此您将创建一个“新的”html元素,因此您不需要ng-model。

编辑模型正如马克在他的评论中提到的,你没有理由不能使用ng-,只是为了遵守约定。

通过在你的指令中显式地创建一个作用域(一个‘’作用域),该指令的作用域不能访问父作用域上的‘

  • ’变量(这就是为什么,我想,你想要使用ng-

)。

  • 我从你的指令中删除了ngModel,并用一个你可以更改为whatever.
  • The的自定义名称替换它,这使得它仍然有效,那就是在作用域中加'=‘符号。签出'scope‘标题下的文档docs

通常,如果希望指令中的值始终映射到父范围中的值,则指令应使用隔离作用域(您这样做是正确的),并使用'=‘类型作用域。

票数 211
EN

Stack Overflow用户

发布于 2013-06-03 23:00:39

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

具有新作用域的

  • ,该作用域复制ngModel
  • 的作用域与在链接

上执行编译的作用域相同

代码语言:javascript
复制
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
  };
});
代码语言:javascript
复制
.some {
  border: 1px solid #cacaca;
  padding: 10px;
}
代码语言:javascript
复制
<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时。因此,它可以归结为:

  • 您是否要替换单个元素:只需替换它,保留作用域不变,但请注意,在v2.0中不建议使用replace:

replace(‘myReplacedDirective’,function($compile) { return { restrict:'E',template:'',replace: true };replace使用:

app.directive('myDirectiveWithScope',function() { return { restrict:'E',scope:{ ngModel:'=',},template:'‘};});

票数 69
EN

Stack Overflow用户

发布于 2014-03-25 13:40:41

这并不复杂:在你的指令中,使用一个别名:scope:{alias:'=ngModel'}

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

在html中,像往常一样使用

代码语言:javascript
复制
<dateselect ng-model="birthday"></dateselect>
票数 54
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14115701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档