ChatGPT解决这个技术问题 Extra ChatGPT

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

我正在尝试创建一个指令,该指令将创建一个与创建指令的元素具有相同 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

R
Roy Truelove

编辑:这个答案很旧,可能已经过时了。只是一个提醒,所以它不会让人们误入歧途。我不再使用 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 是将现有的 html 元素与范围内的值链接。由于您自己创建了一个指令,因此您正在创建一个“新”html 元素,因此您不需要 ng-model。

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

通过在指令中显式创建范围(“隔离”范围),指令的范围无法访问父范围上的“名称”变量(我认为这就是您想要使用 ng-model 的原因)。

我从您的指令中删除了 ngModel 并将其替换为您可以更改为任何名称的自定义名称。

使这一切仍然有效的是范围内的“=”符号。查看“范围”标题下的文档文档。

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


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

我综合了所有答案,现在有两种使用 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: '=', }, // 注意标签没有被复制 template: '

', 替换: true }; }); app.directive('myDirectiveWithChildScope', function($compile) { return { restrict: 'E', scope: true, // 注意标签在范围模板中是如何可见的:'
', replace: true, link: function ($scope, element) { // element 将是获取原始指令上的 ng-model 的 div 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: '
', replace: true, link: function ($scope, element) { // element 将是获取原始指令上的 ng-model 的 div 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: '', replace: true }; }); app.directive('myReplacedDirectiveChild', function($compile) { return { restrict: 'E', scope: true, template: '', replace: true }; }); app.directive('myReplacedDirective', function($compile) { return { restrict: 'E', template: '', replace: true }; }); .some { 边框:1px 实心 #cacaca;填充:10px; }
这个范围值 , label: "{{label}}"
  • 带有新的隔离范围(来自父级的标签):
  • 带有新的子作用域:
  • 相同范围:
  • 替换元素,隔离范围:
  • 替换元素,子范围:
  • 替换元素,相同范围:

尝试输入chi ld 范围的,它们将值复制到子范围中,这会破坏与父范围的链接。

还要注意删除 jQuery 是如何做到的,所以只有 new-isolate-scope 版本有效。

最后请注意,replace+isolate 作用域仅适用于 AngularJS >=1.2.0

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

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

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

您是否替换单个元素:只需替换它,不理会范围,但请注意替换在 v2.0 中已弃用: app.directive('myReplacedDirective', function($compile) { return { restrict: 'E', template : '', 替换: true }; });

否则使用这个: app.directive('myDirectiveWithScope', function() { return { restrict: 'E', scope: { ngModel: '=', }, template: '

' }; });


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

没那么复杂:在您的指令中,使用别名: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 这样的库时,这要容易得多。谢谢!
C
Community

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

其余的请参见Roys answer


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

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

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

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

这样,无需 hack - 您使用的是 Angular 的内置 ng-model


M
Mathew Berg

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

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

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


N
Niels Steenbeek

从 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

我发现如果你确实使用了“=”而不是“<”,那么它是有效的,否则这是使用组件的最佳实践。我不确定这个答案的“YourController 内部”部分是什么意思,这不是在组件内设置 ngModel 吗?
@MarcStober 在“YourController 内部”中,我只想表明 ngModel 可用作 getter 和 setter。在本例中,$ctrl.result 将变为“x”。
好的。我认为重要的另一部分是您还可以在控制器模板中执行 input ng-model="$ctrl.ngModel" 并且它也将与 $ctrl.result 同步。
b
btm1

创建隔离范围是不可取的。我会避免使用范围属性并做这样的事情。 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);
        }
    };
}]);