加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – require:’ngModel’的意思是什么?

发布时间:2020-12-17 09:08:25 所属栏目:安全 来源:网络整理
导读:这是我的指令的HTML: textarea data-modal="modal" data-mydir ng:model="abc"/textarea 在我的指令,我有这: return { require: 'ngModel',replace: true,scope: { modal: '=modal',ngModel: '=',pid: '=pid' }, 有人可以告诉我,require的意义是什么:’
这是我的指令的HTML:
<textarea data-modal="modal" data-mydir ng:model="abc"></textarea>

在我的指令,我有这:

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

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

我很困惑,因为当我把它改变为数据模式我得到一个来自Angular的消息

Controller 'ngModel',required by directive 'textarea',can't be found!
require指令给出了指令的控制器,您将其命名为链接函数的第四个参数。 (您可以使用^在父元素上查找控制器;?使其可选。)所以require:’ngModel’为您提供ngModel指令的控制器, which is an ngModelController

可以编写指令控制器以提供其他指令可以使用的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控制器从colorpicker获取和设置颜色的值。看到这个JSFiddle例子:http://jsfiddle.net/BinaryMuse/AnMhx/

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

the AngularJS homepage的底部示例也使用此功能(除非使用自定义控制器,而不是ngModel)。

至于指令的外壳,例如,ngModel vs ng-model vs data-ng-model:虽然Angular支持在DOM上使用多个表单,但当你按名称引用指令时(例如,当创建指令时,或者使用require),你总是使用lowerCamelCase形式的名字。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读