你何时会使用" @" Angular 1.5绑定"<"?

时间:2017-01-17 16:16:43

标签: angularjs

因此,Angular 1.5文档对于这两个用户的不同用例有些不清楚......

如果我使用"<"我能够消除括号的使用。对于像这样的字符串绑定:

    <cookie-consent-button
        ng-if="app.bundleConfig.adchoices.displayType"
        display-type="app.bundleConfig.adchoices.displayType"
        ghostery-link="app.bundleConfig.adchoices.link[vm.currentLanguage]">
    </cookie-consent-button>
(function() {
    'use strict';

    angular
        .module('app.directives')
        .component('cookieConsentButton', {
            bindings: {
                displayType: '<',
                ghosteryLink: '<'
            },
            templateUrl: 'app/components/cookieConsentButton/cookieConsentButton.html'
        });

})();

而不是使用&#34; @&#34;绑定我必须这样做:

    <cookie-consent-button
        ng-if="app.bundleConfig.adchoices.displayType"
        display-type="{{app.bundleConfig.adchoices.displayType}}"
        ghostery-link="{{app.bundleConfig.adchoices.link[vm.currentLanguage]}}">
    </cookie-consent-button>
(function() {
    'use strict';

    angular
        .module('app.directives')
        .component('cookieConsentButton', {
            bindings: {
                displayType: '@',
                ghosteryLink: '@'
            },
            templateUrl: 'app/components/cookieConsentButton/cookieConsentButton.html'
        });

})();

所以对我来说,似乎我可以通过使用&#34;&lt;&#34;而不是&#34; @&#34; ---。使用&#34; @&#34;有什么好处吗?在所有或是&#34;&lt;&#34;新的方式?

3 个答案:

答案 0 :(得分:0)

价值&#34; @&#34; "Directive Definition Object" documentation,section&#34; scope&#34;:

中描述了组件隔离范围的属性
  

@@attr - 将本地范围属性绑定到DOM的值   属性。 结果始终是字符串,因为DOM属性是   字符串

因此,您可以编写没有大括号的值。

相反(documentation here):

  

<符号表示从1.5开始可用的单向绑定。

因此,作为绑定变量的值,您需要定义一个评估变量的角度表达式。因此,您使用大括号。

答案 1 :(得分:0)

来自Angular documentation

@

  

@@attr - 将本地范围属性绑定到DOM的值   属性。如果未指定attr名称,则假定属性名称与本地名称相同。

&LT;

  

<<attr - 在a之间设置单向(单向)绑定   局部范围属性和通过属性attr传递的表达式。

答案 2 :(得分:0)

@<之间的巨大差异是@旨在用于静态字符串值绑定,一个例子是绑定是在模板中而不是在模板中定义的零件。例如,您可以在组件的模板中使用它

<child-component mode="read-only"></child-component>

使用<绑定,并且在childComponent中,您将得到mode = 'read-only 1)您不必在组件的控制器中设置$scope.mode = "read-only"。 2)如果您想传递该值,则不必评估模板中的值(注意:如果您使用mode={{mode}}绑定,通常会将<放在模板中。 )您传递的是值而不是引用。如果您需要传递引用,则应使用'&lt;'代替。

总之,如果您的绑定是string数据类型且值不会更改(即:您不关心它的$onChanges),请使用@。否则,使用<进行单向绑定。

相关问题