【问题标题】:what's the meaning of '=?' in angularJS directive isolate scope declaration?'=' 是什么意思?在 angularJS 指令中隔离范围声明?
【发布时间】:2013-12-25 05:08:36
【问题描述】:

equals后面的问号有特殊含义吗?即:

scope: {foo: '=?'}

上面的意思是“如果 'foo' 无法解决,就不要引发错误吗?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    Yes:

    “隔离”作用域采用对象散列,该散列定义了一组从父作用域派生的本地作用域属性。这些本地属性对于模板的别名值很有用。本地定义是本地范围属性到其源的哈希:

    ==attr - 在本地范围之间设置双向绑定 属性和通过值定义的名称的父范围属性 attr 属性。如果未指定 attr 名称,则 假定属性名称与本地名称相同。给定 <widget my-attr="parentModel">scope: { localModel:'=myAttr' } 的小部件定义,然后小部件范围属性localModel 将 在父作用域上反映parentModel 的值。任何更改 parentModel 将反映在 localModel 和任何更改 localModel 将反映在 parentModel 中。 如果父范围 属性不存在,它会抛出一个 NON_ASSIGNABLE_MODEL_EXPRESSION 异常。您可以避免这种行为 使用=?=?attr 将属性标记为可选。

    它应该在影响范围属性的每个摘要上触发预期的错误:

    parentSet = parentGet.assign || function() {
    // reset the change, or we will throw this exception on every $digest
    lastValue = scope[scopeName] = parentGet(parentScope);
         throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
         ' (directive: ' + newScopeDirective.name + ')');
    };
    
    //...
    
    
    if (parentValue !== scope[scopeName]) {
        // we are out of sync and need to copy
        if (parentValue !== lastValue) {
            // parent changed and it has precedence
            lastValue = scope[scopeName] = parentValue;
        } else {
            // if the parent can be assigned then do so
            parentSet(parentScope, lastValue = scope[scopeName]);
        }
    }
    

    【讨论】:

    • 有道理,但为什么this directive 不抛出异常。父范围属性不存在且范围分配未使用“=?”
    • 似乎只有在设置值时才会抛出错误,比如这里:plnkr.co/edit/OSpaC6sPE0hY9yAeFghr?p=preview
    • @cebor 目前已在答案中链接,但这里有一个更直接的链接:docs.angularjs.org/api/ng/service/…
    • 虽然我个人希望它直接记录在范围部分而不是 $compile 中。
    • 感谢您的回答,我已经使用 Angular 一年多了,但从未找到“=?”指令上的选项。你让我很开心;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2015-09-02
    • 2012-12-27
    • 2019-10-21
    相关资源
    最近更新 更多