javascript - AngularJS ngModelController 基本问题

标签 javascript angularjs angularjs-directive

在 ngModelController 示例的 Angular 文档中,javascript 文件说:

angular.module('customControl', []).
    directive('contenteditable', function() {
        return {
            restrict: 'A', // only activate on element attribute
            require: '?ngModel', // get a hold of NgModelController
            ...

为什么“ngModel”指的是 NgModelController?为什么不呢,"require: '?ngModelController"从命名的 Angular 来看似乎更合适。

此外,使用 $setViewValue() 函数更新模型与使用 $watch() 函数监视指令范围内模型的变化有什么区别?

谢谢!

最佳答案

Why does "ngModel" refers to the NgModelController? Why isn't it, "require: '?ngModelController" That seems more appropriate from a naming perspective.

因为 require 属性用于要求 controller 指令。例如,ngModel 指令有一个 controller 属性,该属性具有 $setViewValue 和一些其他函数。如果你正在制作一个自定义指令,你可以为它创建一个 Controller ,然后其他指令可以通过说 require: '?yourDirective'require: '^yourDirective' 来访问它> 或 require: 'yourDirective'

来自 Angular 文档:

controller - Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives if they request it by name (see require attribute). This allows the directives to communicate with each other and augment each other's behavior.

require - Require another controller be passed into current directive linking function. The require takes a name of the directive controller to pass in. If no such controller can be found an error is raised.

您可以阅读更多here .

关于javascript - AngularJS ngModelController 基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17055357/

相关文章:

javascript - Json 结果 MVC Controller 通过 Jquery 传输到 Google map

javascript - Angular 的 RouteProvider 和传递范围

javascript - Angular - 仅当您单击 div 的特定区域时,div 上的 ng-click 才有效

javascript - Angular Material Sidenav 不覆盖 Scroll 上的全屏

javascript - AngularJs - 从指令获取默认 HTML

javascript - 使用事件委托(delegate)时获取当前冒泡阶段的目标

Javascript promise : Iterate over all object keys arrays and then resolve

javascript - 如何在文档的 <head> 部分创建 Angular 指令?

javascript - 了解函数中 mouseenter 链接的类

angularjs - Nodejs 中的 req.body 为空 :{}?