angularjs - require : 'ngModel' ? 是什么意思

标签 angularjs

这是我的指令的 HTML:

<textarea data-modal="modal" data-mydir ng:model="abc"></textarea>

在我的指令中我有这个:

return {
  require: 'ngModel',
  replace: true,
  scope: {
    modal: '=modal',
    ngModel: '=',
    pid: '=pid'
  }
}

有人可以告诉我, require: ngModel 的意义是什么?我在许多不同的指令中看到了这一点。我可以称之为数据模式吗?

我很困惑,因为当我将其更改为data-modal时,我收到来自 Angular 的消息

Controller 'ngModel', required by directive 'textarea', can't be found!

最佳答案

require 指令为您提供了您命名为 link 函数的第四个参数的指令的 Controller 。 (您可以使用 ^ 在父元素上查找 Controller ;? 使其可选。)因此 require: 'ngModel' 为您提供ngModel 指令的 Controller which is an ngModelController .

可以编写指令 Controller 来提供其他指令可以使用的 API;通过 ngModelController,您可以访问 ngModel 中内置的特殊功能,包括获取和设置值。考虑以下示例:

<input color-picker ng-model="project.color">
app.directive('colorPicker', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      element.colorPicker({
        // initialize the color to the color on the scope
        pickerDefault: scope.color,
        // update the ngModel whenever we pick a new color
        onColorChange: function(id, newValue) {
          scope.$apply(function() {
            ngModel.$setViewValue(newValue);
          });
        }
      });

      // update the color picker whenever the value on the scope changes
      ngModel.$render = function() {
        element.val(ngModel.$modelValue);
        element.change();                
      };
    }
  }
});

该指令使用 ngModel Controller 从颜色选择器获取和设置颜色值。请参阅此 JSFiddle 示例:http://jsfiddle.net/BinaryMuse/AnMhx/

如果您使用 require: 'ngModel',您可能不应该在您的代码中使用 ngModel: '='隔离范围; ngModelController 为您提供更改值所需的所有访问权限。

the AngularJS homepage 上的底部示例也使用此功能(除了使用自定义 Controller ,而不是 ngModel)。

<小时/>

对于指令的大小写,例如,ngModel vs ng-model vs data-ng-model:而 Angular 支持在 DOM 上使用多种形式,当您通过名称引用指令时(例如,创建指令或使用 require 时),您始终使用名称的小驼峰形式。

关于angularjs - require : 'ngModel' ? 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20930592/

相关文章:

javascript - 使用元素插入 ng-view 的 ng-view 的 Angular 动画父 div

javascript - 路由在 angularjs 中不起作用

src 上的 AngularJS 动画图像更改

javascript - Express.js 应用程序尝试使用 Angular : Uncaught Error: [$injector:nomod] and Uncaught Error: [$injector:modulerr]

javascript - 通知 Promise Angular 删除回调

AngularJS 性能 - 太多观察者?

javascript - 将 html div 导出到字符串

c - 如何通信 AngularJS 的 $http 路由和用 C 编程开发的 API

javascript - 为不同的客户端编写 JavaScript

javascript - AngluarJS 和 Firebase,使用服务更新表