【问题标题】:What is the significance of '?ngModel' when creating an AngularJS directive?创建 AngularJS 指令时,'?ngModel' 的意义是什么?
【发布时间】:2014-01-02 19:08:16
【问题描述】:
我正在研究新的 ng-book。关于过滤器的章节包括使用以下代码定义解析器的部分:
angular.module('myApp')
.directive('oneToTen', function() {
return {
require: '?ngModel';
我第一次看到“?ngModel”语法,Angular API 文档并没有提供太多帮助。这个语法是什么意思?
谢谢!
【问题讨论】:
标签:
javascript
angularjs
angularjs-directive
【解决方案1】:
? 是可选指令,^ 是父指令
http://docs.angularjs.org/api/ng.$compile
(no prefix) - Locate the required controller on the current element. Throw an error if not found.
? - Attempt to locate the required controller or pass null to the link fn if not found.
^ - Locate the required controller by searching the element's parents. Throw an error if not found.
?^ - Attempt to locate the required controller by searching the element's parents or pass null to the link fn if not found.
【解决方案2】:
必填可以解释为:
[?][^][directiveName]。
它用于指定应该使用哪个指令控制器(“继承自”)。因此,例如指令<column-item> 需要找到父控制器<crtl-grid>。有几个符号可以与此属性一起使用,也可以组合使用:
^ = 表示 Angular 查找 DOM 以找到指令。
? = 它表示 angular 该指令是可选的,如果找不到,则 angular 不会抛出异常。
所以 ?ngModel 是说 ngModel 需要与该指令一起声明。