在AngularJS的指令范围内,“@”和“=”有什么区别?

时间:2022-01-11 03:38:48

I've read the AngularJS documentation on the topic carefully, and then fiddled around with a directive. Here's the fiddle.

我仔细阅读了关于这个主题的AngularJS文档,然后胡乱地编写了一个指令。这是小提琴。

And here are some relevant snippets:

以下是一些相关的片段:

  • From the HTML:

    从HTML:

    <pane bi-title="title" title="{{title}}">{{text}}</pane>
    
  • From the pane directive:

    从面板的指令:

    scope: { biTitle: '=', title: '@', bar: '=' },
    

There are several things I don't get:

有几件事我不明白:

  • Why do I have to use "{{title}}" with '@' and "title" with '='?
  • 为什么我必须用“{{}}”加上“@”和“标题”加上“=”?
  • Can I also access the parent scope directly, without decorating my element with an attribute?
  • 我也可以直接访问父范围,而不用使用属性来修饰元素吗?
  • The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?
  • 文档说“通常希望通过表达式和父作用域从隔离作用域传递数据”,但是对于双向绑定来说,这似乎也很有效。为什么表达路径会更好?

I found another fiddle that shows the expression solution too: http://jsfiddle.net/maxisam/QrCXh/

我还发现了另一个显示表达式解决方案的东西:http://jsfiddle.net/maxisam/QrCXh/

17 个解决方案

#1


1101  

Why do I have to use "{{title}}" with '@' and "title" with '='?

为什么我必须用“{{}}”加上“@”和“标题”加上“=”?

@ binds a local/directive scope property to the evaluated value of the DOM attribute. If you use title=title1 or title="title1", the value of DOM attribute "title" is simply the string title1. If you use title="{{title}}", the value of the DOM attribute "title" is the interpolated value of {{title}}, hence the string will be whatever parent scope property "title" is currently set to. Since attribute values are always strings, you will always end up with a string value for this property in the directive's scope when using @.

@将本地/指令范围属性绑定到DOM属性的计算值。如果您使用title=title1或title="title1",那么DOM属性"title"的值就是string title1。如果您使用title="{{{}}",那么DOM属性"title"的值就是{{title}的插补值,因此该字符串将是当前设置为的父作用域属性"title"的值。由于属性值始终是字符串,所以在使用@时,在该指令的作用域中,您总是会得到该属性的字符串值。

= binds a local/directive scope property to a parent scope property. So with =, you use the parent model/scope property name as the value of the DOM attribute. You can't use {{}}s with =.

=将本地/指令范围属性绑定到父范围属性。因此,对于=,使用父模型/范围属性名作为DOM属性的值。不能使用{}和=。

With @, you can do things like title="{{title}} and then some" -- {{title}} is interpolated, then the string "and them some" is concatenated with it. The final concatenated string is what the local/directive scope property gets. (You can't do this with =, only @.)

使用@,您可以做一些事情,如title="{{title}} "和some" - {title}被插入,然后字符串"and them some"被它连接起来。最后的连接字符串是本地/指令范围属性得到的。(你不能用=,只能用@。)

With @, you will need to use attr.$observe('title', function(value) { ... }) if you need to use the value in your link(ing) function. E.g., if(scope.title == "...") won't work like you expect. Note that this means you can only access this attribute asynchronously. You don't need to use $observe() if you are only using the value in a template. E.g., template: '<div>{{title}}</div>'.

对于@,您需要使用attr。观察美元(“标题”,函数(值){…})如果需要在链接(ing)函数中使用值。例如,如果范围。它不会像你期望的那样工作。注意,这意味着只能异步地访问此属性。如果只在模板中使用值,则不需要使用$observe()。例如,模板:“< div > { {标题} } < / div >”。

With =, you don't need to use $observe.

与=,您不需要使用$observe。

Can I also access the parent scope directly, without decorating my element with an attribute?

我也可以直接访问父范围,而不用使用属性来修饰元素吗?

Yes, but only if you don't use an isolate scope. Remove this line from your directive

是的,但前提是您不使用隔离范围。从指令中删除这一行

scope: { ... }

范围:{…}

and then your directive will not create a new scope. It will use the parent scope. You can then access all of the parent scope properties directly.

然后你的指令不会创建一个新的范围。它将使用父范围。然后可以直接访问所有父范围属性。

The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

文档说“通常希望通过表达式和父作用域从隔离作用域传递数据”,但是对于双向绑定来说,这似乎也很有效。为什么表达路径会更好?

Yes, bidirectional binding allows the local/directive scope and the parent scope to share data. "Expression binding" allows the directive to call an expression (or function) defined by a DOM attribute -- and you can also pass data as arguments to the expression or function. So, if you don't need to share data with the parent -- you just want to call a function defined in the parent scope -- you can use the & syntax.

是的,双向绑定允许本地/指令范围和父范围共享数据。“表达式绑定”允许指令调用由DOM属性定义的表达式(或函数),也可以将数据作为参数传递给表达式或函数。因此,如果不需要与父对象共享数据——只需调用父范围中定义的函数——可以使用&语法。

See also

另请参阅

#2


521  

There are a lot of great answers here, but I would like to offer my perspective on the differences between @, =, and & binding that proved useful for me.

这里有很多很好的答案,但是我想提供我对@、=和&绑定之间的差异的看法,这对我来说是有用的。

All three bindings are ways of passing data from your parent scope to your directive's isolated scope through the element's attributes:

这三个绑定都是通过元素的属性将数据从父作用域传递到指令的隔离作用域的方法:

  1. @ binding is for passing strings. These strings support {{}} expressions for interpolated values. For example: . The interpolated expression is evaluated against directive's parent scope.

    @绑定用于传递字符串。这些字符串支持用于插入值的{{}表达式。例如:。插值表达式是根据指令的父作用域进行计算的。

  2. = binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope. Changes to one model affects the other, and vice versa.

    =绑定是双向模型绑定。父作用域中的模型与指令的隔离作用域中的模型相关联。一个模型的变化会影响另一个模型,反之亦然。

  3. & binding is for passing a method into your directive's scope so that it can be called within your directive. The method is pre-bound to the directive's parent scope, and supports arguments. For example if the method is hello(name) in parent scope, then in order to execute the method from inside your directive, you must call $scope.hello({name:'world'})

    & binding是将一个方法传递到您的指令的范围中,以便它可以在您的指令中被调用。该方法预先绑定到该指令的父作用域,并支持参数。例如,如果方法在父作用域中是hello(name),那么为了从您的指令中执行该方法,您必须调用$scope.hello({name:'world'})

I find that it's easier to remember these differences by referring to the scope bindings by a shorter description:

我发现,通过更短的描述来参考范围绑定,更容易记住这些差异:

  • @ Attribute string binding
  • @属性字符串绑定
  • = Two-way model binding
  • =双向模型绑定
  • & Callback method binding
  • &绑定回调方法

The symbols also make it clearer as to what the scope variable represents inside of your directive's implementation:

这些符号还使它更清楚地说明在指令的实现中范围变量代表什么:

  • @ string
  • @字符串
  • = model
  • =模型
  • & method
  • &方法

In order of usefulness (for me anyways):

按用途排序(对我来说):

  1. =
  2. =
  3. @
  4. @
  5. &
  6. &

#3


59  

The = means bi-directional binding, so a reference to a variable to the parent scope. This means, when you change the variable in the directive, it will be changed in the parent scope as well.

=意味着双向绑定,因此将变量引用到父范围。这意味着,当您在指令中更改变量时,它也将在父作用域中更改。

@ means the variable will be copied (cloned) into the directive.

@表示变量将被复制(克隆)到指令中。

As far as I know, <pane bi-title="{{title}}" title="{{title}}">{{text}}</pane> should work too. bi-title will receive the parent scope variable value, which can be changed in the directive.

据我所知, {text}} 也应该可以。bi-title将接收父作用域变量值,该值可以在指令中更改。

If you need to change several variables in the parent scope, you could execute a function on the parent scope from within the directive (or pass data via a service).

如果需要更改父作用域中的几个变量,可以在该指令中执行父作用域上的一个函数(或者通过服务传递数据)。

#4


35  

If you would like to see more how this work with a live example. http://jsfiddle.net/juanmendez/k6chmnch/

如果您想了解更多关于这个示例的工作原理。http://jsfiddle.net/juanmendez/k6chmnch/

var app = angular.module('app', []);
app.controller("myController", function ($scope) {
    $scope.title = "binding";
});
app.directive("jmFind", function () {
    return {
        replace: true,
        restrict: 'C',
        transclude: true,
        scope: {
            title1: "=",
            title2: "@"
        },
        template: "<div><p>{{title1}} {{title2}}</p></div>"
    };
});

#5


35  

@ get as string

@得到字符串

  • This does not create any bindings whatsoever. You're simply getting the word you passed in as a string
  • 这不会创建任何绑定。你只是得到你作为字符串传入的单词

= 2 way binding

= 2绑定方式

  • changes made from the controller will be reflected in the reference held by the directive, and vice-versa
  • 由控制器做出的更改将在指令所持有的引用中反映出来,反之亦然。

& This behaves a bit differently, because the scope gets a function that returns the object that was passed in. I'm assuming this was necessary to make it work. The fiddle should make this clear.

它的行为稍有不同,因为作用域获得一个函数,返回传入的对象。我想这是必要的。小提琴应该弄清楚这一点。

  • After calling this getter function, the resulting object behaves as follows:
    • if a function was passed: then the function is executed in the parent (controller) closure when called
    • 如果传递了一个函数:那么当调用时,函数将在父(控制器)闭包中执行
    • if a non-function was passed in: simply get a local copy of the object that has no bindings
    • 如果传入了非函数:只需获得没有绑定的对象的本地副本
  • 调用这个getter函数之后,结果对象的行为如下:如果传递了一个函数:那么当调用父(控制器)闭包时,如果传递了一个非函数,则在父(控制器)闭包中执行函数:简单地获取一个没有绑定的对象的本地副本


This fiddle should demonstrate how they work. Pay special attention to the scope functions with get... in the name to hopefully better understand what I mean about &

这把小提琴应该演示它们是如何工作的。特别注意get的作用域函数。希望你能更好地理解我所说的&

#6


31  

There are three ways scope can be added in the directive:

在该指令中可以添加三种方法:

  1. Parent scope: This is the default scope inheritance.
  2. 父范围:这是默认的范围继承。

The directive and its parent(controller/directive inside which it lies) scope is same. So any changes made to the scope variables inside directive are reflected in the parent controller as well. You don't need to specify this as it is the default.

该指令及其父(它所在的控制器/指令)作用域是相同的。因此,在指令内对作用域变量所做的任何更改也反映在父控制器中。您不需要指定这个,因为它是默认的。

  1. Child scope: directive creates a child scope which inherits from the parent scope if you specify the scope variable of the directive as true.
  2. 子作用域:指令创建一个子作用域,如果将指令的作用域变量指定为true,则该作用域从父作用域继承。

Here, if you change the scope variables inside directive, it won't reflect in the parent scope, but if you change the property of a scope variable, that is reflected in the parent scope, as you actually modified the scope variable of the parent.

在这里,如果您在指令中更改作用域变量,它不会在父作用域中反映出来,但是如果您更改作用域变量的属性,它会在父作用域中反映出来,因为您实际上修改了父作用域变量。

Example,

的例子,

app.directive("myDirective", function(){

    return {
        restrict: "EA",
        scope: true,
        link: function(element, scope, attrs){
            scope.somvar = "new value"; //doesnot reflect in the parent scope
            scope.someObj.someProp = "new value"; //reflects as someObj is of parent, we modified that but did not override.
        }
    };
});
  1. Isolated scope: This is used when you want to create the scope that does not inherit from the controller scope.
  2. 隔离范围:当您想要创建不从控制器范围继承的范围时,使用隔离范围。

This happens when you are creating plugins as this makes the directive generic since it can be placed in any HTML and does not gets affected by its parent scope.

当您创建插件时就会发生这种情况,因为这使该指令成为通用的,因为它可以放在任何HTML中,并且不会受到父作用域的影响。

Now, if you don't want any interaction with the parent scope, then you can just specify scope as an empty object. like,

现在,如果不希望与父作用域进行任何交互,那么可以将作用域指定为一个空对象。就像,

scope: {} //this does not interact with the parent scope in any way

Mostly this is not the case as we need some interaction with the parent scope, so we want some of the values/ changes to pass through. For this reason, we use:

大多数情况下不是这样的,因为我们需要与父范围进行一些交互,所以我们希望通过一些值/更改。为此,我们使用:

1. "@"   (  Text binding / one-way binding )
2. "="   ( Direct model binding / two-way binding )
3. "&"   ( Behaviour binding / Method binding  )

@ means that the changes from the controller scope will be reflected in the directive scope but if you modify the value in the directive scope, the controller scope variable will not get affected.

@表示来自控制器范围的更改将反映在指令范围中,但是如果您修改指令范围中的值,控制器范围变量将不会受到影响。

@ always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}.

@总是期望映射的属性是一个表达式。这是非常重要的;因为要使“@”前缀生效,我们需要将属性值包装在{{}内。

= is bidirectional so if you change the variable in directive scope, the controller scope variable gets affected as well

=是双向的,所以如果你在指令范围内改变变量,控制器范围变量也会受到影响

& is used to bind controller scope method so that if needed we can call it from the directive

&用于绑定控制器范围方法,以便在需要时可以从指令调用它

The advantage here is that the name of the variable need not be same in controller scope and directive scope.

这里的优点是,在控制器范围和指令范围中变量的名称不需要相同。

Example, the directive scope has a variable "dirVar" which syncs with variable "contVar" of the controller scope. This gives a lot of power and generalization to the directive as one controller can sync with variable v1 while another controller using the same directive can ask dirVar to sync with variable v2.

例如,指令作用域有一个变量“dirVar”,它与控制器作用域的变量“contVar”同步。这给指令带来了很大的力量和泛化,因为一个控制器可以与变量v1同步,而另一个控制器使用相同的指令可以要求dirVar与变量v2同步。

Below is the example of usage:

下面是使用示例:

The directive and controller are:

指令和控制器为:

 var app = angular.module("app", []);
 app.controller("MainCtrl", function( $scope ){
    $scope.name = "Harry";
    $scope.color = "#333333";
    $scope.reverseName = function(){
     $scope.name = $scope.name.split("").reverse().join("");
    };
    $scope.randomColor = function(){
        $scope.color = '#'+Math.floor(Math.random()*16777215).toString(16);
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {
            name: "@",
            color: "=",
            reverse: "&"
        },
        link: function(element, scope, attrs){
           //do something like
           $scope.reverse(); 
          //calling the controllers function
        }
    };
});

And the html(note the differnce for @ and =):

和html(注意@和=的区别):

<div my-directive
  class="directive"
  name="{{name}}"
  reverse="reverseName()"
  color="color" >
</div>

Here is a link to the blog which describes it nicely.

这是一个博客的链接,很好地描述了它。

#7


19  

Simply we can use:-

只是我们可以使用:-

  1. @ :- for String values for one way Data binding. in one way data binding you can only pass scope value to directive

    -为单向数据绑定的字符串值。在某种程度上,数据绑定只能将范围值传递给指令

  2. = :- for object value for two way data binding. in two way data binding you can change the scope value in directive as well as in html also.

    =:-对于两路数据绑定的对象值。在双向数据绑定中,您可以更改指令的范围值,也可以更改html中的范围值。

  3. & :- for methods and functions.

    &:-用于方法和函数。

EDIT

In our Component definition for Angular version 1.5 And above
there are four different type of bindings:

在我们的角版本1.5和以上的组件定义中,有四种不同类型的绑定:

  1. = Two-way data binding :- if we change the value,it automatically update
  2. =双向数据绑定:-如果我们改变值,它会自动更新
  3. < one way binding :- when we just want to read a parameter from a parent scope and not update it.

    <单向绑定:-当我们只想从父作用域读取参数而不更新它时。< p>

  4. @ this is for String Parameters

    这是字符串参数

  5. & this is for Callbacks in case your component needs to output something to its parent scope

    &这是用于回调,以防组件需要向其父范围输出某些内容

#8


10  

I created a little HTML file that contains Angular code demonstrating the differences between them:

我创建了一个包含角码的HTML文件,展示了它们之间的差异:

https://gist.github.com/RobertAKARobin/a02426c375596f0bef89

https://gist.github.com/RobertAKARobin/a02426c375596f0bef89

<!DOCTYPE html>
<html>
  <head>
    <title>Angular</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="myCtrl as VM">
      <a my-dir
        attr1="VM.sayHi('Juan')"
        attr2="VM.sayHi('Juan')"
        attr3="VM.sayHi('Juan')"></a>
    </div>
    <script>
    angular.module("myApp", [])
    .controller("myCtrl", [function(){
      var vm = this;
      vm.sayHi = function(name){
        return ("Hey there, " + name);
      }
    }])
    .directive("myDir", [function(){
      var directive = {
        scope: { attr1: "=", attr2: "@", attr3: "&" },
        link: function(scope){
          console.log(scope.attr1);   // logs "Hey there, Juan"
          console.log(scope.attr2);   // logs "VM.sayHi('Juan')"
          console.log(scope.attr3);   // logs "function (a){return h(c,a)}"
          console.log(scope.attr3()); // logs "Hey there, Juan"
        }
      }
      return directive;
    }]);
    </script>
  </body>
</html>

#9


6  

The = way is 2-way binding, which lets you to have live changes inside your directive. When someone changes that variable out of directive, you will have that changed data inside your directive, but @ way is not two-ways binding. It works like Text. You bind once, and you will have only its value.

方法是双向绑定,它允许您在指令内部进行实时更改。当有人从指令中更改该变量时,您将在指令中更改数据,但是@ way并不是双向绑定。它的工作原理就像文本。你绑定一次,你就只有它的价值。

To get it more clearly, you can use this great article:

为了更清楚地了解它,你可以使用这篇伟大的文章:

AngularJS Directive Scope '@' and '='

AngularJS指令范围'@'和'='

#10


3  

@ local scope property is used to access string values that are defined outside the directive.

@ local scope属性用于访问在指令之外定义的字符串值。

= In cases where you need to create a two-way binding between the outer scope and the directive’s isolate scope you can use the = character.

=在需要在外部范围和指令的隔离范围之间创建双向绑定的情况下,可以使用=字符。

& local scope property allows the consumer of a directive to pass in a function that the directive can invoke.

本地作用域属性允许指令的使用者传入指令可以调用的函数。

Kindly check the below link which gives you clear understanding with examples.I found it really very useful so thought of sharing it.

请查看下面的链接,通过示例使您清楚地理解。我发现它真的很有用,所以想要分享它。

http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

#11


3  

I implemented all the possible options in a fiddle.

我用小提琴实现了所有可能的选项。

It deals with all the options:

它处理所有的选项:

scope:{
    name:'&'
},

scope:{
    name:'='
},

scope:{
    name:'@'
},

scope:{

},

scope:true,

https://jsfiddle.net/rishulmatta/v7xf2ujm

https://jsfiddle.net/rishulmatta/v7xf2ujm

#12


2  

Even when the scope is local, as in your example, you may access the parent scope through the property $parent. Assume in the code below, that title is defined on the parent scope. You may then access title as $parent.title:

即使范围是本地的,例如在您的示例中,您也可以通过属性$parent访问父范围。假设在下面的代码中,标题是在父范围中定义的。然后您可以以$parent.title访问title。

link : function(scope) { console.log(scope.$parent.title) },
template : "the parent has the title {{$parent.title}}"

However in most cases the same effect is better obtained using attributes.

然而,在大多数情况下,使用属性更好地获得相同的效果。

An example of where I found the "&" notation, which is used "to pass data from the isolated scope via an expression and to the parent scope", useful (and a two-way databinding could not be used) was in a directive for rendering a special datastructure inside an ng-repeat.

我找到“&”表示法的一个例子,它用于“通过表达式将数据从隔离范围传递到父范围”,这个例子很有用(而且不能使用双向数据库),用于在ng-repeat中呈现特殊的数据结构。

<render data = "record" deleteFunction = "dataList.splice($index,1)" ng-repeat = "record in dataList" > </render>

One part of the rendering was a delete button and here it was useful to attach a deletefunction from the outside scope via &. Inside the render-directive it looks like

呈现的一部分是一个delete按钮,在这里,通过&从外部范围附加一个deletefunction非常有用。在render指令里面看起来是这样的

scope : { data = "=", deleteFunction = "&"},
template : "... <button ng-click = "deleteFunction()"></button>"

2-way databinding i.e. data = "=" can not be used as the delete function would run on every $digest cycle, which is not good, as the record is then immediately deleted and never rendered.

不能使用2路数据库,即data =" =",因为delete函数将在每个$digest循环中运行,这是不好的,因为记录将立即被删除,并且永远不会被呈现。

#13


1  

@ and = see other answers.

参见其他答案。

One gotcha about &
TL;DR;
& gets expression (not only function like in examples in other answers) from a parent, and sets it as a function in the directive, that calls the expression. And this function has the ability to replace any variable (even function name) of expression, by passing an object with the variables.

一个关于;&获取表达式(不只是在其他答案中的例子中的函数),并将其设置为指令中的函数,即调用表达式。这个函数可以通过用变量传递对象来替换表达式的任何变量(甚至函数名)。

explained
& is an expression reference, that means if you pass something like <myDirective expr="x==y"></myDirective>
in the directive this expr will be a function, that calls the expression, like:
function expr(){return x == y}.
so in directive's html <button ng-click="expr()"></button> will call the expression. In js of the directive just $scope.expr() will call the expression too.
The expression will be called with $scope.x and $scope.y of the parent.
You have the ability to override the parameters!
If you set them by call, e.g. <button ng-click="expr({x:5})"></button>
then the expression will be called with your parameter x and parent's parameter y.
You can override both.
Now you know, why <button ng-click="functionFromParent({x:5})"></button> works.
Because it just calls the expression of parent (e.g. <myDirective functionFromParent="function1(x)"></myDirective>) and replaces possible values with your specified parameters, in this case x.
it could be:
<myDirective functionFromParent="function1(x) + 5"></myDirective>
or
<myDirective functionFromParent="function1(x) + z"></myDirective>
with child call:
<button ng-click="functionFromParent({x:5, z: 4})"></button>.
or even with function replacement:
<button ng-click="functionFromParent({function1: myfn, x:5, z: 4})"></button>.

解释&是一个表达式引用,这意味着如果您传递类似 在该指令中,这个表达式将是一个函数,它调用表达式,如:function expr(){return x= y}。在指令的html 将调用表达式。在指令的js中,只有$scope.expr()也会调用表达式。这个表达式将使用$scope调用。x和美元范围。y的父母。您有能力覆盖参数!如果您通过调用设置它们,例如,然后用参数x和父参数y调用表达式。您可以同时覆盖这两个参数。”现在您知道为什么

it just an expression, does not matter if it is a function, or many functions, or just comparison. And you can replace any variable of this expression.

它只是一个表达式,不管它是一个函数,还是许多函数,还是只是比较。你可以替换这个表达式的任何变量。

Examples:
directive template vs called code:
parent has defined $scope.x, $scope.y:
parent template: <myDirective expr="x==y"></myDirective>
<button ng-click="expr()"></button> calls $scope.x==$scope.y
<button ng-click="expr({x: 5})"></button> calls 5 == $scope.y
<button ng-click="expr({x:5, y:6})"></button> calls 5 == 6

示例:指令模板vs调用代码:父类定义了$scope。x美元范围。y:父模板: 调用5 == $scope。y <按钮ng-click = expr({ x:5 y:6 })”> 调用5 == 6。

parent has defined $scope.function1, $scope.x, $scope.y:
parent template: <myDirective expr="function1(x) + y"></myDirective>

父母已经定义了美元范围。function1,美元范围。x美元范围。y:父模板:

<button ng-click="expr()"></button> calls $scope.function1($scope.x) + $scope.y
<button ng-click="expr({x: 5})"></button> calls $scope.function1(5) + $scope.y
<button ng-click="expr({x:5, y:6})"></button> calls $scope.function1(5) + 6
directive has $scope.myFn as function:
<button ng-click="expr({function1: myFn, x:5, y:6})"></button> calls $scope.myFn(5) + 6

<按钮ng-click = " expr()“> 调用$scope.function1($scope.x) + $scope。y <按钮ng-click = expr({ x:5 })”> 调用$scope.function1(5) + $scope。y <按钮ng-click = expr({ x:5 y:6 })”> 调用$scope.function1(5) + 6指令有$scope。myFn作为函数: 调用$scope.myFn(5) + 6

#14


0  

Why do I have to use "{{title}}" with '@' and "title" with '='?

为什么我必须用“{{}}”加上“@”和“标题”加上“=”?

When you use {{title}} , only the parent scope value will be passed to directive view and evaluated. This is limited to one way, meaning that change will not be reflected in parent scope. You can use '=' when you want to reflect the changes done in child directive to parent scope also. This is two way.

当您使用{{title}}时,只有父范围值将被传递给指示视图并进行评估。这仅限于一种方式,这意味着更改不会反映在父范围中。当您希望将子指令中的更改反映到父范围时,也可以使用'='。这是两个方法。

Can I also access the parent scope directly, without decorating my element with an attribute?

我也可以直接访问父范围,而不用使用属性来修饰元素吗?

When directive has scope attribute in it ( scope : {} ), then you no longer will be able to access parent scope directly. But still it is possible to access it via scope.$parent etc. If you remove scope from directive, it can be accessed directly.

当指令中包含作用域属性(作用域:{})时,您将不再能够直接访问父作用域。但是仍然可以通过范围访问它。$parent等。如果从指令中删除范围,可以直接访问它。

The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

文档说“通常希望通过表达式和父作用域从隔离作用域传递数据”,但是对于双向绑定来说,这似乎也很有效。为什么表达路径会更好?

It depends based on context. If you want to call an expression or function with data, you use & and if you want share data , you can use biderectional way using '='

这取决于上下文。如果你想用数据调用表达式或函数,你可以使用&如果你想共享数据,你可以使用'='

You can find the differences between multiple ways of passing data to directive at below link:

你可以在以下连结找到将数据传送至指令的不同方法:

AngularJS – Isolated Scopes – @ vs = vs &

AngularJS -隔离范围- @ vs = vs &

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

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

#15


0  

@ Attribute string binding (one way) = Two-way model binding & Callback method binding

@属性字符串绑定(单向)=双向模型绑定和回调方法绑定。

#16


0  

the main difference between them is just

他们之间的主要区别是公正的

@ Attribute string binding
= Two-way model binding
& Callback method binding

#17


0  

@ binds a local/directive scope property to the evaluated value of the DOM attribute. = binds a local/directive scope property to a parent scope property. & binding is for passing a method into your directive's scope so that it can be called within your directive.

@将本地/指令范围属性绑定到DOM属性的计算值。=将本地/指令范围属性绑定到父范围属性。& binding是将一个方法传递到您的指令的范围中,以便它可以在您的指令中被调用。

@ Attribute string binding = Two-way model binding & Callback method binding

@属性字符串绑定=双向模型绑定和回调方法绑定

#1


1101  

Why do I have to use "{{title}}" with '@' and "title" with '='?

为什么我必须用“{{}}”加上“@”和“标题”加上“=”?

@ binds a local/directive scope property to the evaluated value of the DOM attribute. If you use title=title1 or title="title1", the value of DOM attribute "title" is simply the string title1. If you use title="{{title}}", the value of the DOM attribute "title" is the interpolated value of {{title}}, hence the string will be whatever parent scope property "title" is currently set to. Since attribute values are always strings, you will always end up with a string value for this property in the directive's scope when using @.

@将本地/指令范围属性绑定到DOM属性的计算值。如果您使用title=title1或title="title1",那么DOM属性"title"的值就是string title1。如果您使用title="{{{}}",那么DOM属性"title"的值就是{{title}的插补值,因此该字符串将是当前设置为的父作用域属性"title"的值。由于属性值始终是字符串,所以在使用@时,在该指令的作用域中,您总是会得到该属性的字符串值。

= binds a local/directive scope property to a parent scope property. So with =, you use the parent model/scope property name as the value of the DOM attribute. You can't use {{}}s with =.

=将本地/指令范围属性绑定到父范围属性。因此,对于=,使用父模型/范围属性名作为DOM属性的值。不能使用{}和=。

With @, you can do things like title="{{title}} and then some" -- {{title}} is interpolated, then the string "and them some" is concatenated with it. The final concatenated string is what the local/directive scope property gets. (You can't do this with =, only @.)

使用@,您可以做一些事情,如title="{{title}} "和some" - {title}被插入,然后字符串"and them some"被它连接起来。最后的连接字符串是本地/指令范围属性得到的。(你不能用=,只能用@。)

With @, you will need to use attr.$observe('title', function(value) { ... }) if you need to use the value in your link(ing) function. E.g., if(scope.title == "...") won't work like you expect. Note that this means you can only access this attribute asynchronously. You don't need to use $observe() if you are only using the value in a template. E.g., template: '<div>{{title}}</div>'.

对于@,您需要使用attr。观察美元(“标题”,函数(值){…})如果需要在链接(ing)函数中使用值。例如,如果范围。它不会像你期望的那样工作。注意,这意味着只能异步地访问此属性。如果只在模板中使用值,则不需要使用$observe()。例如,模板:“< div > { {标题} } < / div >”。

With =, you don't need to use $observe.

与=,您不需要使用$observe。

Can I also access the parent scope directly, without decorating my element with an attribute?

我也可以直接访问父范围,而不用使用属性来修饰元素吗?

Yes, but only if you don't use an isolate scope. Remove this line from your directive

是的,但前提是您不使用隔离范围。从指令中删除这一行

scope: { ... }

范围:{…}

and then your directive will not create a new scope. It will use the parent scope. You can then access all of the parent scope properties directly.

然后你的指令不会创建一个新的范围。它将使用父范围。然后可以直接访问所有父范围属性。

The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

文档说“通常希望通过表达式和父作用域从隔离作用域传递数据”,但是对于双向绑定来说,这似乎也很有效。为什么表达路径会更好?

Yes, bidirectional binding allows the local/directive scope and the parent scope to share data. "Expression binding" allows the directive to call an expression (or function) defined by a DOM attribute -- and you can also pass data as arguments to the expression or function. So, if you don't need to share data with the parent -- you just want to call a function defined in the parent scope -- you can use the & syntax.

是的,双向绑定允许本地/指令范围和父范围共享数据。“表达式绑定”允许指令调用由DOM属性定义的表达式(或函数),也可以将数据作为参数传递给表达式或函数。因此,如果不需要与父对象共享数据——只需调用父范围中定义的函数——可以使用&语法。

See also

另请参阅

#2


521  

There are a lot of great answers here, but I would like to offer my perspective on the differences between @, =, and & binding that proved useful for me.

这里有很多很好的答案,但是我想提供我对@、=和&绑定之间的差异的看法,这对我来说是有用的。

All three bindings are ways of passing data from your parent scope to your directive's isolated scope through the element's attributes:

这三个绑定都是通过元素的属性将数据从父作用域传递到指令的隔离作用域的方法:

  1. @ binding is for passing strings. These strings support {{}} expressions for interpolated values. For example: . The interpolated expression is evaluated against directive's parent scope.

    @绑定用于传递字符串。这些字符串支持用于插入值的{{}表达式。例如:。插值表达式是根据指令的父作用域进行计算的。

  2. = binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope. Changes to one model affects the other, and vice versa.

    =绑定是双向模型绑定。父作用域中的模型与指令的隔离作用域中的模型相关联。一个模型的变化会影响另一个模型,反之亦然。

  3. & binding is for passing a method into your directive's scope so that it can be called within your directive. The method is pre-bound to the directive's parent scope, and supports arguments. For example if the method is hello(name) in parent scope, then in order to execute the method from inside your directive, you must call $scope.hello({name:'world'})

    & binding是将一个方法传递到您的指令的范围中,以便它可以在您的指令中被调用。该方法预先绑定到该指令的父作用域,并支持参数。例如,如果方法在父作用域中是hello(name),那么为了从您的指令中执行该方法,您必须调用$scope.hello({name:'world'})

I find that it's easier to remember these differences by referring to the scope bindings by a shorter description:

我发现,通过更短的描述来参考范围绑定,更容易记住这些差异:

  • @ Attribute string binding
  • @属性字符串绑定
  • = Two-way model binding
  • =双向模型绑定
  • & Callback method binding
  • &绑定回调方法

The symbols also make it clearer as to what the scope variable represents inside of your directive's implementation:

这些符号还使它更清楚地说明在指令的实现中范围变量代表什么:

  • @ string
  • @字符串
  • = model
  • =模型
  • & method
  • &方法

In order of usefulness (for me anyways):

按用途排序(对我来说):

  1. =
  2. =
  3. @
  4. @
  5. &
  6. &

#3


59  

The = means bi-directional binding, so a reference to a variable to the parent scope. This means, when you change the variable in the directive, it will be changed in the parent scope as well.

=意味着双向绑定,因此将变量引用到父范围。这意味着,当您在指令中更改变量时,它也将在父作用域中更改。

@ means the variable will be copied (cloned) into the directive.

@表示变量将被复制(克隆)到指令中。

As far as I know, <pane bi-title="{{title}}" title="{{title}}">{{text}}</pane> should work too. bi-title will receive the parent scope variable value, which can be changed in the directive.

据我所知, {text}} 也应该可以。bi-title将接收父作用域变量值,该值可以在指令中更改。

If you need to change several variables in the parent scope, you could execute a function on the parent scope from within the directive (or pass data via a service).

如果需要更改父作用域中的几个变量,可以在该指令中执行父作用域上的一个函数(或者通过服务传递数据)。

#4


35  

If you would like to see more how this work with a live example. http://jsfiddle.net/juanmendez/k6chmnch/

如果您想了解更多关于这个示例的工作原理。http://jsfiddle.net/juanmendez/k6chmnch/

var app = angular.module('app', []);
app.controller("myController", function ($scope) {
    $scope.title = "binding";
});
app.directive("jmFind", function () {
    return {
        replace: true,
        restrict: 'C',
        transclude: true,
        scope: {
            title1: "=",
            title2: "@"
        },
        template: "<div><p>{{title1}} {{title2}}</p></div>"
    };
});

#5


35  

@ get as string

@得到字符串

  • This does not create any bindings whatsoever. You're simply getting the word you passed in as a string
  • 这不会创建任何绑定。你只是得到你作为字符串传入的单词

= 2 way binding

= 2绑定方式

  • changes made from the controller will be reflected in the reference held by the directive, and vice-versa
  • 由控制器做出的更改将在指令所持有的引用中反映出来,反之亦然。

& This behaves a bit differently, because the scope gets a function that returns the object that was passed in. I'm assuming this was necessary to make it work. The fiddle should make this clear.

它的行为稍有不同,因为作用域获得一个函数,返回传入的对象。我想这是必要的。小提琴应该弄清楚这一点。

  • After calling this getter function, the resulting object behaves as follows:
    • if a function was passed: then the function is executed in the parent (controller) closure when called
    • 如果传递了一个函数:那么当调用时,函数将在父(控制器)闭包中执行
    • if a non-function was passed in: simply get a local copy of the object that has no bindings
    • 如果传入了非函数:只需获得没有绑定的对象的本地副本
  • 调用这个getter函数之后,结果对象的行为如下:如果传递了一个函数:那么当调用父(控制器)闭包时,如果传递了一个非函数,则在父(控制器)闭包中执行函数:简单地获取一个没有绑定的对象的本地副本


This fiddle should demonstrate how they work. Pay special attention to the scope functions with get... in the name to hopefully better understand what I mean about &

这把小提琴应该演示它们是如何工作的。特别注意get的作用域函数。希望你能更好地理解我所说的&

#6


31  

There are three ways scope can be added in the directive:

在该指令中可以添加三种方法:

  1. Parent scope: This is the default scope inheritance.
  2. 父范围:这是默认的范围继承。

The directive and its parent(controller/directive inside which it lies) scope is same. So any changes made to the scope variables inside directive are reflected in the parent controller as well. You don't need to specify this as it is the default.

该指令及其父(它所在的控制器/指令)作用域是相同的。因此,在指令内对作用域变量所做的任何更改也反映在父控制器中。您不需要指定这个,因为它是默认的。

  1. Child scope: directive creates a child scope which inherits from the parent scope if you specify the scope variable of the directive as true.
  2. 子作用域:指令创建一个子作用域,如果将指令的作用域变量指定为true,则该作用域从父作用域继承。

Here, if you change the scope variables inside directive, it won't reflect in the parent scope, but if you change the property of a scope variable, that is reflected in the parent scope, as you actually modified the scope variable of the parent.

在这里,如果您在指令中更改作用域变量,它不会在父作用域中反映出来,但是如果您更改作用域变量的属性,它会在父作用域中反映出来,因为您实际上修改了父作用域变量。

Example,

的例子,

app.directive("myDirective", function(){

    return {
        restrict: "EA",
        scope: true,
        link: function(element, scope, attrs){
            scope.somvar = "new value"; //doesnot reflect in the parent scope
            scope.someObj.someProp = "new value"; //reflects as someObj is of parent, we modified that but did not override.
        }
    };
});
  1. Isolated scope: This is used when you want to create the scope that does not inherit from the controller scope.
  2. 隔离范围:当您想要创建不从控制器范围继承的范围时,使用隔离范围。

This happens when you are creating plugins as this makes the directive generic since it can be placed in any HTML and does not gets affected by its parent scope.

当您创建插件时就会发生这种情况,因为这使该指令成为通用的,因为它可以放在任何HTML中,并且不会受到父作用域的影响。

Now, if you don't want any interaction with the parent scope, then you can just specify scope as an empty object. like,

现在,如果不希望与父作用域进行任何交互,那么可以将作用域指定为一个空对象。就像,

scope: {} //this does not interact with the parent scope in any way

Mostly this is not the case as we need some interaction with the parent scope, so we want some of the values/ changes to pass through. For this reason, we use:

大多数情况下不是这样的,因为我们需要与父范围进行一些交互,所以我们希望通过一些值/更改。为此,我们使用:

1. "@"   (  Text binding / one-way binding )
2. "="   ( Direct model binding / two-way binding )
3. "&"   ( Behaviour binding / Method binding  )

@ means that the changes from the controller scope will be reflected in the directive scope but if you modify the value in the directive scope, the controller scope variable will not get affected.

@表示来自控制器范围的更改将反映在指令范围中,但是如果您修改指令范围中的值,控制器范围变量将不会受到影响。

@ always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}.

@总是期望映射的属性是一个表达式。这是非常重要的;因为要使“@”前缀生效,我们需要将属性值包装在{{}内。

= is bidirectional so if you change the variable in directive scope, the controller scope variable gets affected as well

=是双向的,所以如果你在指令范围内改变变量,控制器范围变量也会受到影响

& is used to bind controller scope method so that if needed we can call it from the directive

&用于绑定控制器范围方法,以便在需要时可以从指令调用它

The advantage here is that the name of the variable need not be same in controller scope and directive scope.

这里的优点是,在控制器范围和指令范围中变量的名称不需要相同。

Example, the directive scope has a variable "dirVar" which syncs with variable "contVar" of the controller scope. This gives a lot of power and generalization to the directive as one controller can sync with variable v1 while another controller using the same directive can ask dirVar to sync with variable v2.

例如,指令作用域有一个变量“dirVar”,它与控制器作用域的变量“contVar”同步。这给指令带来了很大的力量和泛化,因为一个控制器可以与变量v1同步,而另一个控制器使用相同的指令可以要求dirVar与变量v2同步。

Below is the example of usage:

下面是使用示例:

The directive and controller are:

指令和控制器为:

 var app = angular.module("app", []);
 app.controller("MainCtrl", function( $scope ){
    $scope.name = "Harry";
    $scope.color = "#333333";
    $scope.reverseName = function(){
     $scope.name = $scope.name.split("").reverse().join("");
    };
    $scope.randomColor = function(){
        $scope.color = '#'+Math.floor(Math.random()*16777215).toString(16);
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {
            name: "@",
            color: "=",
            reverse: "&"
        },
        link: function(element, scope, attrs){
           //do something like
           $scope.reverse(); 
          //calling the controllers function
        }
    };
});

And the html(note the differnce for @ and =):

和html(注意@和=的区别):

<div my-directive
  class="directive"
  name="{{name}}"
  reverse="reverseName()"
  color="color" >
</div>

Here is a link to the blog which describes it nicely.

这是一个博客的链接,很好地描述了它。

#7


19  

Simply we can use:-

只是我们可以使用:-

  1. @ :- for String values for one way Data binding. in one way data binding you can only pass scope value to directive

    -为单向数据绑定的字符串值。在某种程度上,数据绑定只能将范围值传递给指令

  2. = :- for object value for two way data binding. in two way data binding you can change the scope value in directive as well as in html also.

    =:-对于两路数据绑定的对象值。在双向数据绑定中,您可以更改指令的范围值,也可以更改html中的范围值。

  3. & :- for methods and functions.

    &:-用于方法和函数。

EDIT

In our Component definition for Angular version 1.5 And above
there are four different type of bindings:

在我们的角版本1.5和以上的组件定义中,有四种不同类型的绑定:

  1. = Two-way data binding :- if we change the value,it automatically update
  2. =双向数据绑定:-如果我们改变值,它会自动更新
  3. < one way binding :- when we just want to read a parameter from a parent scope and not update it.

    <单向绑定:-当我们只想从父作用域读取参数而不更新它时。< p>

  4. @ this is for String Parameters

    这是字符串参数

  5. & this is for Callbacks in case your component needs to output something to its parent scope

    &这是用于回调,以防组件需要向其父范围输出某些内容

#8


10  

I created a little HTML file that contains Angular code demonstrating the differences between them:

我创建了一个包含角码的HTML文件,展示了它们之间的差异:

https://gist.github.com/RobertAKARobin/a02426c375596f0bef89

https://gist.github.com/RobertAKARobin/a02426c375596f0bef89

<!DOCTYPE html>
<html>
  <head>
    <title>Angular</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="myCtrl as VM">
      <a my-dir
        attr1="VM.sayHi('Juan')"
        attr2="VM.sayHi('Juan')"
        attr3="VM.sayHi('Juan')"></a>
    </div>
    <script>
    angular.module("myApp", [])
    .controller("myCtrl", [function(){
      var vm = this;
      vm.sayHi = function(name){
        return ("Hey there, " + name);
      }
    }])
    .directive("myDir", [function(){
      var directive = {
        scope: { attr1: "=", attr2: "@", attr3: "&" },
        link: function(scope){
          console.log(scope.attr1);   // logs "Hey there, Juan"
          console.log(scope.attr2);   // logs "VM.sayHi('Juan')"
          console.log(scope.attr3);   // logs "function (a){return h(c,a)}"
          console.log(scope.attr3()); // logs "Hey there, Juan"
        }
      }
      return directive;
    }]);
    </script>
  </body>
</html>

#9


6  

The = way is 2-way binding, which lets you to have live changes inside your directive. When someone changes that variable out of directive, you will have that changed data inside your directive, but @ way is not two-ways binding. It works like Text. You bind once, and you will have only its value.

方法是双向绑定,它允许您在指令内部进行实时更改。当有人从指令中更改该变量时,您将在指令中更改数据,但是@ way并不是双向绑定。它的工作原理就像文本。你绑定一次,你就只有它的价值。

To get it more clearly, you can use this great article:

为了更清楚地了解它,你可以使用这篇伟大的文章:

AngularJS Directive Scope '@' and '='

AngularJS指令范围'@'和'='

#10


3  

@ local scope property is used to access string values that are defined outside the directive.

@ local scope属性用于访问在指令之外定义的字符串值。

= In cases where you need to create a two-way binding between the outer scope and the directive’s isolate scope you can use the = character.

=在需要在外部范围和指令的隔离范围之间创建双向绑定的情况下,可以使用=字符。

& local scope property allows the consumer of a directive to pass in a function that the directive can invoke.

本地作用域属性允许指令的使用者传入指令可以调用的函数。

Kindly check the below link which gives you clear understanding with examples.I found it really very useful so thought of sharing it.

请查看下面的链接,通过示例使您清楚地理解。我发现它真的很有用,所以想要分享它。

http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

#11


3  

I implemented all the possible options in a fiddle.

我用小提琴实现了所有可能的选项。

It deals with all the options:

它处理所有的选项:

scope:{
    name:'&'
},

scope:{
    name:'='
},

scope:{
    name:'@'
},

scope:{

},

scope:true,

https://jsfiddle.net/rishulmatta/v7xf2ujm

https://jsfiddle.net/rishulmatta/v7xf2ujm

#12


2  

Even when the scope is local, as in your example, you may access the parent scope through the property $parent. Assume in the code below, that title is defined on the parent scope. You may then access title as $parent.title:

即使范围是本地的,例如在您的示例中,您也可以通过属性$parent访问父范围。假设在下面的代码中,标题是在父范围中定义的。然后您可以以$parent.title访问title。

link : function(scope) { console.log(scope.$parent.title) },
template : "the parent has the title {{$parent.title}}"

However in most cases the same effect is better obtained using attributes.

然而,在大多数情况下,使用属性更好地获得相同的效果。

An example of where I found the "&" notation, which is used "to pass data from the isolated scope via an expression and to the parent scope", useful (and a two-way databinding could not be used) was in a directive for rendering a special datastructure inside an ng-repeat.

我找到“&”表示法的一个例子,它用于“通过表达式将数据从隔离范围传递到父范围”,这个例子很有用(而且不能使用双向数据库),用于在ng-repeat中呈现特殊的数据结构。

<render data = "record" deleteFunction = "dataList.splice($index,1)" ng-repeat = "record in dataList" > </render>

One part of the rendering was a delete button and here it was useful to attach a deletefunction from the outside scope via &. Inside the render-directive it looks like

呈现的一部分是一个delete按钮,在这里,通过&从外部范围附加一个deletefunction非常有用。在render指令里面看起来是这样的

scope : { data = "=", deleteFunction = "&"},
template : "... <button ng-click = "deleteFunction()"></button>"

2-way databinding i.e. data = "=" can not be used as the delete function would run on every $digest cycle, which is not good, as the record is then immediately deleted and never rendered.

不能使用2路数据库,即data =" =",因为delete函数将在每个$digest循环中运行,这是不好的,因为记录将立即被删除,并且永远不会被呈现。

#13


1  

@ and = see other answers.

参见其他答案。

One gotcha about &
TL;DR;
& gets expression (not only function like in examples in other answers) from a parent, and sets it as a function in the directive, that calls the expression. And this function has the ability to replace any variable (even function name) of expression, by passing an object with the variables.

一个关于;&获取表达式(不只是在其他答案中的例子中的函数),并将其设置为指令中的函数,即调用表达式。这个函数可以通过用变量传递对象来替换表达式的任何变量(甚至函数名)。

explained
& is an expression reference, that means if you pass something like <myDirective expr="x==y"></myDirective>
in the directive this expr will be a function, that calls the expression, like:
function expr(){return x == y}.
so in directive's html <button ng-click="expr()"></button> will call the expression. In js of the directive just $scope.expr() will call the expression too.
The expression will be called with $scope.x and $scope.y of the parent.
You have the ability to override the parameters!
If you set them by call, e.g. <button ng-click="expr({x:5})"></button>
then the expression will be called with your parameter x and parent's parameter y.
You can override both.
Now you know, why <button ng-click="functionFromParent({x:5})"></button> works.
Because it just calls the expression of parent (e.g. <myDirective functionFromParent="function1(x)"></myDirective>) and replaces possible values with your specified parameters, in this case x.
it could be:
<myDirective functionFromParent="function1(x) + 5"></myDirective>
or
<myDirective functionFromParent="function1(x) + z"></myDirective>
with child call:
<button ng-click="functionFromParent({x:5, z: 4})"></button>.
or even with function replacement:
<button ng-click="functionFromParent({function1: myfn, x:5, z: 4})"></button>.

解释&是一个表达式引用,这意味着如果您传递类似 在该指令中,这个表达式将是一个函数,它调用表达式,如:function expr(){return x= y}。在指令的html 将调用表达式。在指令的js中,只有$scope.expr()也会调用表达式。这个表达式将使用$scope调用。x和美元范围。y的父母。您有能力覆盖参数!如果您通过调用设置它们,例如,然后用参数x和父参数y调用表达式。您可以同时覆盖这两个参数。”现在您知道为什么

it just an expression, does not matter if it is a function, or many functions, or just comparison. And you can replace any variable of this expression.

它只是一个表达式,不管它是一个函数,还是许多函数,还是只是比较。你可以替换这个表达式的任何变量。

Examples:
directive template vs called code:
parent has defined $scope.x, $scope.y:
parent template: <myDirective expr="x==y"></myDirective>
<button ng-click="expr()"></button> calls $scope.x==$scope.y
<button ng-click="expr({x: 5})"></button> calls 5 == $scope.y
<button ng-click="expr({x:5, y:6})"></button> calls 5 == 6

示例:指令模板vs调用代码:父类定义了$scope。x美元范围。y:父模板: 调用5 == $scope。y <按钮ng-click = expr({ x:5 y:6 })”> 调用5 == 6。

parent has defined $scope.function1, $scope.x, $scope.y:
parent template: <myDirective expr="function1(x) + y"></myDirective>

父母已经定义了美元范围。function1,美元范围。x美元范围。y:父模板:

<button ng-click="expr()"></button> calls $scope.function1($scope.x) + $scope.y
<button ng-click="expr({x: 5})"></button> calls $scope.function1(5) + $scope.y
<button ng-click="expr({x:5, y:6})"></button> calls $scope.function1(5) + 6
directive has $scope.myFn as function:
<button ng-click="expr({function1: myFn, x:5, y:6})"></button> calls $scope.myFn(5) + 6

<按钮ng-click = " expr()“> 调用$scope.function1($scope.x) + $scope。y <按钮ng-click = expr({ x:5 })”> 调用$scope.function1(5) + $scope。y <按钮ng-click = expr({ x:5 y:6 })”> 调用$scope.function1(5) + 6指令有$scope。myFn作为函数: 调用$scope.myFn(5) + 6

#14


0  

Why do I have to use "{{title}}" with '@' and "title" with '='?

为什么我必须用“{{}}”加上“@”和“标题”加上“=”?

When you use {{title}} , only the parent scope value will be passed to directive view and evaluated. This is limited to one way, meaning that change will not be reflected in parent scope. You can use '=' when you want to reflect the changes done in child directive to parent scope also. This is two way.

当您使用{{title}}时,只有父范围值将被传递给指示视图并进行评估。这仅限于一种方式,这意味着更改不会反映在父范围中。当您希望将子指令中的更改反映到父范围时,也可以使用'='。这是两个方法。

Can I also access the parent scope directly, without decorating my element with an attribute?

我也可以直接访问父范围,而不用使用属性来修饰元素吗?

When directive has scope attribute in it ( scope : {} ), then you no longer will be able to access parent scope directly. But still it is possible to access it via scope.$parent etc. If you remove scope from directive, it can be accessed directly.

当指令中包含作用域属性(作用域:{})时,您将不再能够直接访问父作用域。但是仍然可以通过范围访问它。$parent等。如果从指令中删除范围,可以直接访问它。

The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

文档说“通常希望通过表达式和父作用域从隔离作用域传递数据”,但是对于双向绑定来说,这似乎也很有效。为什么表达路径会更好?

It depends based on context. If you want to call an expression or function with data, you use & and if you want share data , you can use biderectional way using '='

这取决于上下文。如果你想用数据调用表达式或函数,你可以使用&如果你想共享数据,你可以使用'='

You can find the differences between multiple ways of passing data to directive at below link:

你可以在以下连结找到将数据传送至指令的不同方法:

AngularJS – Isolated Scopes – @ vs = vs &

AngularJS -隔离范围- @ vs = vs &

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

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

#15


0  

@ Attribute string binding (one way) = Two-way model binding & Callback method binding

@属性字符串绑定(单向)=双向模型绑定和回调方法绑定。

#16


0  

the main difference between them is just

他们之间的主要区别是公正的

@ Attribute string binding
= Two-way model binding
& Callback method binding

#17


0  

@ binds a local/directive scope property to the evaluated value of the DOM attribute. = binds a local/directive scope property to a parent scope property. & binding is for passing a method into your directive's scope so that it can be called within your directive.

@将本地/指令范围属性绑定到DOM属性的计算值。=将本地/指令范围属性绑定到父范围属性。& binding是将一个方法传递到您的指令的范围中,以便它可以在您的指令中被调用。

@ Attribute string binding = Two-way model binding & Callback method binding

@属性字符串绑定=双向模型绑定和回调方法绑定