Javascript angularJS中&与@和=的区别是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14908133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:17:22  来源:igfitidea点击:

What is the difference between & vs @ and = in angularJS

javascriptangularjs

提问by Nur Rony

I am very new to AngularJS. can anybody explain me the difference among these AngularJS operators: &, @ and =when isolating scope with proper example.

我对 AngularJS 很陌生。任何人都可以向我解释这些 AngularJS 运算符之间的区别:&, @ and =当用适当的例子隔离范围时。

回答by cliff.meyers

@allows a value defined on the directive attribute to be passed to the directive's isolate scope. The value could be a simple string value (myattr="hello") or it could be an AngularJS interpolated string with embedded expressions (myattr="my_{{helloText}}"). Think of it as "one-way" communication from the parent scope into the child directive. John Lindquist has a series of short screencasts explaining each of these. Screencast on @ is here: https://egghead.io/lessons/angularjs-isolate-scope-attribute-binding

@允许将指令属性上定义的值传递给指令的隔离范围。该值可以是一个简单的字符串值 ( myattr="hello") 或者它可以是一个带有嵌入表达式的 AngularJS 内插字符串 ( myattr="my_{{helloText}}")。将其视为从父作用域到子指令的“单向”通信。John Lindquist 有一系列简短的截屏视频来解释其中的每一个。@ 上的截屏视频在这里:https: //egghead.io/lessons/angularjs-isolate-scope-attribute-binding

&allows the directive's isolate scope to pass values into the parent scope for evaluation in the expression defined in the attribute. Note that the directive attribute is implicitly an expression and does not use double curly brace expression syntax. This one is tougher to explain in text. Screencast on & is here: https://egghead.io/lessons/angularjs-isolate-scope-expression-binding

&允许指令的隔离范围将值传递到父范围以在属性中定义的表达式中进行评估。请注意,指令属性是隐式表达式,不使用双花括号表达式语法。这个更难用文字解释。截屏视频在这里:https: //egghead.io/lessons/angularjs-isolate-scope-expression-binding

=sets up a two-way binding expression between the directive's isolate scope and the parent scope. Changes in the child scope are propagated to the parent and vice-versa. Think of = as a combination of @ and &. Screencast on = is here: https://egghead.io/lessons/angularjs-isolate-scope-two-way-binding

=在指令的隔离范围和父范围之间设置双向绑定表达式。子作用域中的更改会传播到父作用域,反之亦然。将 = 视为 @ 和 & 的组合。= 上的截屏视频在这里:https: //egghead.io/lessons/angularjs-isolate-scope-two-way-binding

And finally here is a screencast that shows all three used together in a single view: https://egghead.io/lessons/angularjs-isolate-scope-review

最后,这是一个截屏视频,在一个视图中显示所有三个一起使用:https: //egghead.io/lessons/angularjs-isolate-scope-review

回答by Joy

I would like to explain the concepts from the perspective of JavaScript prototype inheritance. Hopefully help to understand.

我想从JavaScript原型继承的角度来解释这些概念。希望有助于理解。

There are three options to define the scope of a directive:

有三个选项可以定义指令的范围:

  1. scope: false: Angular default. The directive's scope is exactly the one of its parent scope (parentScope).
  2. scope: true: Angular creates a scope for this directive. The scope prototypically inherits from parentScope.
  3. scope: {...}: isolated scope is explained below.
  1. scope: false:角度默认。该指令的作用域正是其父作用域 ( parentScope) 之一。
  2. scope: true: Angular 为此指令创建了一个作用域。范围原型继承自parentScope.
  3. scope: {...}:隔离范围解释如下。

Specifying scope: {...}defines an isolatedScope. An isolatedScopedoes not inherit properties from parentScope, although isolatedScope.$parent === parentScope. It is defined through:

指定scope: {...}定义了一个isolatedScope. AnisolatedScope不从 继承属性parentScope,尽管isolatedScope.$parent === parentScope. 它通过以下方式定义:

app.directive("myDirective", function() {
    return {
        scope: {
            ... // defining scope means that 'no inheritance from parent'.
        },
    }
})

isolatedScopedoes not have direct access to parentScope. But sometimes the directive needs to communicate with the parentScope. They communicate through @, =and &. The topic about using symbols @, =and &are talking about scenarios using isolatedScope.

isolatedScope无法直接访问parentScope. 但有时指令需要与parentScope. 它们通过@=和 进行通信&关于使用符号的主题@=以及&使用isolatedScope.

It is usually used for some common components shared by different pages, like Modals. An isolated scope prevents polluting the global scope and is easy to share among pages.

它通常用于不同页面共享的一些公共组件,例如 Modals。隔离作用域可防止污染全局作用域,并且易于在页面之间共享。

Here is a basic directive: http://jsfiddle.net/7t984sf9/5/. An image to illustrate is:

这是一个基本指令:http: //jsfiddle.net/7t984sf9/5/。要说明的图像是:

enter image description here

在此处输入图片说明

@: one-way binding

@: 单向绑定

@simply passes the property from parentScopeto isolatedScope. It is called one-way binding, which means you cannot modify the value of parentScopeproperties. If you are familiar with JavaScript inheritance, you can understand these two scenarios easily:

@只需将属性从parentScopeto传递过来isolatedScope。它被称为one-way binding,这意味着您不能修改parentScope属性的值。如果你熟悉 JavaScript 继承,你可以很容易地理解这两种场景:

  • If the binding property is a primitive type, like interpolatedPropin the example: you can modify interpolatedProp, but parentProp1would not be changed. However, if you change the value of parentProp1, interpolatedPropwill be overwritten with the new value (when angular $digest).

  • If the binding property is some object, like parentObj: since the one passed to isolatedScopeis a reference, modifying the value will trigger this error:

    TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}

  • 如果绑定属性是原始类型,如interpolatedProp示例中所示:您可以修改interpolatedProp,但parentProp1不会更改。但是,如果更改 的值parentProp1interpolatedProp将被新值覆盖(当 angular $digest 时)。

  • 如果绑定属性是某个对象,例如parentObj:由于传递给的isolatedScope是引用,修改该值将触发此错误:

    TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}

=: two-way binding

=: 双向绑定

=is called two-way binding, which means any modification in childScopewill also update the value in parentScope, and vice versa. This rule works for both primitives and objects. If you change the binding type of parentObjto be =, you will find that you can modify the value of parentObj.x. A typical example is ngModel.

=被调用two-way binding,这意味着任何修改childScope都会更新 中的值parentScope,反之亦然。此规则适用于基元和对象。如果将 的绑定类型更改parentObj=,您会发现可以修改 的值parentObj.x。一个典型的例子是ngModel

&: function binding

&: 函数绑定

&allows the directive to call some parentScopefunction and pass in some value from the directive. For example, check JSFiddle: & in directive scope.

&允许指令调用一些parentScope函数并从指令中传递一些值。例如,检查JSFiddle: & 在指令范围内

Define a clickable template in the directive like:

在指令中定义一个可点击的模板,如:

<div ng-click="vm.onCheck({valueFromDirective: vm.value + ' is from the directive'})">

And use the directive like:

并使用如下指令:

<div my-checkbox value="vm.myValue" on-check="vm.myFunction(valueFromDirective)"></div>

The variable valueFromDirectiveis passed from the directive to the parent controller through {valueFromDirective: ....

变量valueFromDirective从指令通过{valueFromDirective: ....

Reference: Understanding Scopes

参考:了解作用域

回答by jgm

Not my fiddle, but http://jsfiddle.net/maxisam/QrCXh/shows the difference. The key piece is:

不是我的小提琴,但http://jsfiddle.net/maxisam/QrCXh/显示了差异。关键部分是:

           scope:{
            /* NOTE: Normally I would set my attributes and bindings
            to be the same name but I wanted to delineate between 
            parent and isolated scope. */                
            isolatedAttributeFoo:'@attributeFoo',
            isolatedBindingFoo:'=bindingFoo',
            isolatedExpressionFoo:'&'
        }        

回答by Timothy.Li

@: one-way binding

@: 单向绑定

=: two-way binding

=: 双向绑定

&: function binding

&: 函数绑定

回答by Prashanth

AngularJS – Isolated Scopes – @ vs = vs &

AngularJS – 独立作用域 – @ vs = vs &



Short examples with explanation are available at below link :

以下链接提供了带有解释的简短示例:

http://www.codeforeach.com/angularjs/angularjs-isolated-scopes-vs-vs

http://www.codeforeach.com/angularjs/angularjs-isolated-scopes-vs-vs

@ – one way binding

@ – 单向绑定

In directive:

在指令中:

scope : { nameValue : "@name" }

In view:

鉴于:

<my-widget name="{{nameFromParentScope}}"></my-widget>

= – two way binding

= – 双向绑定

In directive:

在指令中:

scope : { nameValue : "=name" },
link : function(scope) {
  scope.name = "Changing the value here will get reflected in parent scope value";
}

In view:

鉴于:

<my-widget name="{{nameFromParentScope}}"></my-widget>

& – Function call

& – 函数调用

In directive :

在指令中:

scope : { nameChange : "&" }
link : function(scope) {
  scope.nameChange({newName:"NameFromIsolaltedScope"});
}

In view:

鉴于:

<my-widget nameChange="onNameChange(newName)"></my-widget>

回答by Peter Nixey

It took me a hell of a long time to really get a handle on this. The key to me was in understanding that "@" is for stuff that you want evaluated in situ and passed through into the directive as a constant where "=" actually passes the object itself.

我花了很长时间才真正掌握这个。对我来说,关键在于理解“@”用于您想要在原位评估并作为常量传递到指令中的东西,其中“=”实际上传递对象本身。

There's a nice blog post that explains this this at: http://blog.ramses.io/technical/AngularJS-the-difference-between-@-&-and-=-when-declaring-directives-using-isolate-scopes

有一篇很好的博客文章解释了这一点:http: //blog.ramses.io/technical/AngularJS-the-difference-between-@-&-and-=-when-declaring-directives-using-isolate-scopes