your programing

AngularJS의 지시문 범위에서 '@'와 '='의 차이점은 무엇입니까?

lovepro 2020. 9. 27. 13:32
반응형

AngularJS의 지시문 범위에서 '@'와 '='의 차이점은 무엇입니까?


주제에 대한 AngularJS 문서를주의 깊게 읽은 다음 지시문을 다루었습니다. 여기에 바이올린이 있습니다.

다음은 몇 가지 관련 스 니펫입니다.

  • HTML에서 :

    <pane bi-title="title" title="{{title}}">{{text}}</pane>
    
  • pane 지시문에서 :

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

내가 이해하지 못하는 몇 가지 사항이 있습니다.

  • "{{title}}"with '@'"title"with 함께 사용해야 하는 이유는 무엇 '='입니까?
  • 속성으로 요소를 장식하지 않고 부모 범위에 직접 액세스 할 수도 있습니까?
  • 문서에는 "표현식을 통해 격리 된 범위에서 부모 범위로 데이터를 전달하는 것이 바람직하다"라고 나와 있지만 양방향 바인딩에서도 잘 작동하는 것 같습니다. 왜 표현 경로가 더 좋을까요?

식 솔루션을 보여주는 또 다른 바이올린을 찾았습니다. http://jsfiddle.net/maxisam/QrCXh/


' @ ' 에는 '{{title}} '을, ' = ' 에는 'title' 을 사용해야하는 이유는 무엇 입니까?

@ 는 로컬 / 지시적 범위 속성을 DOM 속성평가 된 값에 바인딩 합니다 . 당신이 사용하는 경우 title=title1또는 title="title1", DOM 속성 "제목"의 가치는 단순히 문자열입니다 title1. 를 사용하는 경우 title="{{title}}"DOM 속성 "title"의 값은의 보간 된 값 {{title}}이므로 문자열은 현재 설정된 상위 범위 속성 "title"이 무엇이든됩니다. 속성 값은 항상 문자열이므로 @를 사용할 때 지시문 범위에서이 속성에 대한 문자열 값으로 끝납니다 .

= 로컬 / 지시적 범위 속성을 부모 범위 속성에 바인딩 합니다 . 따라서 = 를 사용하면 상위 모델 / 범위 속성 이름을 DOM 속성 값으로 사용합니다. ={{}} 와 함께 s를 사용할 수 없습니다 .

@를 사용하면 다음과 같은 작업을 수행 할 수 있습니다. title="{{title}} and then some"{{title}}이 보간 된 다음 "and them some"문자열이 이에 연결됩니다. 마지막으로 연결된 문자열은 로컬 / 지시문 범위 속성이 가져 오는 것입니다. ( = 로이 작업을 수행 할 수 없으며 @ 만 가능 합니다.)

@ , 당신은 사용해야합니다 attr.$observe('title', function(value) { ... })당신이 당신의 링크 (보내고) 함수의 값을 사용해야하는 경우. 예 : if(scope.title == "...")예상대로 작동하지 않습니다. 이는이 속성에 비동기 적으로 만 액세스 할 수 있음을 의미합니다 . 템플릿의 값만 사용하는 경우 $ observe ()를 사용할 필요가 없습니다. 예 : template: '<div>{{title}}</div>'.

= , 당신은 관찰 $를 사용할 필요가 없습니다.

속성으로 요소를 장식하지 않고 부모 범위에 직접 액세스 할 수도 있습니까?

예,하지만 격리 범위를 사용하지 않는 경우에만 가능합니다. 지시문에서이 줄을 제거하십시오.

scope: { ... }

그러면 지시문이 새 범위를 만들지 않습니다. 부모 범위를 사용합니다. 그런 다음 모든 상위 범위 속성에 직접 액세스 할 수 있습니다.

문서에는 "표현식을 통해 격리 된 범위에서 부모 범위로 데이터를 전달하는 것이 바람직합니다."라고되어 있지만 양방향 바인딩에서도 잘 작동하는 것 같습니다. 왜 표현 경로가 더 좋을까요?

예, 양방향 바인딩을 사용하면 로컬 / 지시문 범위와 상위 범위가 데이터를 공유 할 수 있습니다. "표현식 바인딩"을 사용하면 지시문이 DOM 속성에 의해 정의 된 표현식 (또는 함수)을 호출 할 수 있으며 표현식 또는 함수에 인수로 데이터를 전달할 수도 있습니다. 따라서 부모와 데이터를 공유 할 필요가없는 경우 (부모 범위에 정의 된 함수를 호출하려는 경우) & 구문을 사용할 수 있습니다 .

또한보십시오


이 큰 응답의 많은 현재 위치,하지만 난 사이의 차이점에 대한 나의 관점을 제공하고 싶습니다 @, =그리고 &바인딩 나를 위해 유용한 입증하는.

세 가지 바인딩은 모두 요소의 속성을 통해 부모 범위에서 지시문의 격리 된 범위로 데이터를 전달하는 방법입니다.

  1. @ 바인딩은 문자열을 전달하기위한 것입니다. 이러한 문자열 {{}}은 보간 된 값에 대한 표현식을 지원 합니다. 예 :. 보간 된 식은 지시문의 부모 범위에 대해 평가됩니다.

  2. = 바인딩은 양방향 모델 바인딩 용입니다. 상위 범위의 모델은 지시문의 격리 된 범위에있는 모델에 연결됩니다. 한 모델을 변경하면 다른 모델에 영향을 미치며 그 반대의 경우도 마찬가지입니다.

  3. & binding은 지시문 내에서 호출 될 수 있도록 지시문의 범위에 메소드를 전달하기위한 것입니다. 이 메서드는 지시문의 부모 범위에 미리 바인딩되어 있으며 인수를 지원합니다. 예를 들어 메서드가 부모 범위에서 hello (name)이면 지시문 내에서 메서드를 실행하려면 $ scope.hello ({name : 'world'})를 호출해야합니다.

짧은 설명으로 범위 바인딩을 참조하여 이러한 차이점을 기억하는 것이 더 쉽다는 것을 알았습니다.

  • @ 속성 문자열 바인딩
  • = 양방향 모델 바인딩
  • & 콜백 메서드 바인딩

기호는 또한 지시문의 구현 내에서 범위 변수가 나타내는 내용을 더 명확하게합니다.

  • @
  • = 모델
  • & 방법

유용성 순으로 (어쨌든 나를 위해) :

  1. =
  2. @
  3. &

=수단 양방향 결합하므로 상위 범위에 변수에 대한 참조. 즉, 지시문에서 변수를 변경하면 부모 범위에서도 변경됩니다.

@ 변수가 지시문에 복사 (복제)된다는 의미입니다.

내가 아는 <pane bi-title="{{title}}" title="{{title}}">{{text}}</pane>한도 작동해야합니다. bi-title지시문에서 변경할 수있는 부모 범위 변수 값을받습니다.

부모 범위에서 여러 변수를 변경해야하는 경우 지시문 내에서 부모 범위에서 함수를 실행하거나 서비스를 통해 데이터를 전달할 수 있습니다.


라이브 예제를 통해 이것이 어떻게 작동하는지 더 알고 싶다면. 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>"
    };
});

@ 문자열로 얻다

  • 이것은 어떠한 바인딩도 생성하지 않습니다. 당신은 단순히 당신이 전달한 단어를 문자열로 얻는 것입니다.

= 양방향 바인딩

  • 컨트롤러에서 변경 한 내용은 지침이 보유한 참조에 반영되며 그 반대의 경우도 마찬가지입니다.

&스코프가 에서 전달 된 객체를 반환 하는 함수를 가져 오기 때문에 이것은 약간 다르게 작동합니다 . 나는 이것이 작동하기 위해 필요하다고 가정하고 있습니다. 바이올린은 이것을 명확히해야합니다.

  • 이 getter 함수를 호출 한 후 결과 객체는 다음과 같이 작동합니다.
    • 경우 함수 전달 하였다 호출되면 그 함수는 상위 (컨트롤러) 클로저에서 실행된다
    • 경우 가 아닌 함수가 전달되었습니다 단순히 더 바인딩이없는 개체의 로컬 복사본을 얻을


이 바이올린은 작동 방식을 보여 주어야합니다 . get...내가 의미하는 바를 더 잘 이해하려면 이름에 포함 된 스코프 기능에 특별한주의를 기울이십시오.&


지시문에 범위를 추가 할 수있는 세 가지 방법이 있습니다.

  1. 상위 범위 : 기본 범위 상속입니다.

디렉티브와 그 부모 (컨트롤러 / 디렉티브가있는 디렉티브) 범위는 동일합니다. 따라서 지시문 내의 범위 변수에 대한 변경 사항은 상위 컨트롤러에도 반영됩니다. 기본값이므로 지정할 필요가 없습니다.

  1. 자식 범위 : 지시문의 범위 변수를 true로 지정하면 부모 범위에서 상속되는 자식 범위를 만듭니다.

여기서 지시문 내에서 범위 변수를 변경하면 부모 범위에 반영되지 않지만 범위 변수의 속성을 변경하면 실제로 부모의 범위 변수를 수정 했으므로 부모 범위에 반영됩니다. .

예,

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. 격리 된 범위 : 컨트롤러 범위에서 상속되지 않는 범위를 만들려는 경우 사용됩니다.

이는 플러그인을 생성 할 때 발생합니다. 이는 모든 HTML에 배치 될 수 있고 부모 범위의 영향을받지 않기 때문에 지시문을 일반화하기 때문입니다.

이제 부모 범위와의 상호 작용을 원하지 않는 경우 범위를 빈 개체로 지정할 수 있습니다. 처럼,

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

대부분의 경우 부모 범위와의 상호 작용이 필요하므로 일부 값 / 변경 사항이 전달되기를 원합니다. 이러한 이유로 다음을 사용합니다.

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

@ 는 컨트롤러 범위의 변경 사항이 지시문 범위에 반영되지만 지시문 범위의 값을 수정하면 컨트롤러 범위 변수가 영향을받지 않음을 의미합니다.

@은 항상 매핑 된 속성이 표현식 일 것으로 예상합니다. 이건 매우 중요합니다; "@"접두사가 작동하게하려면 {{}} 안에 속성 값을 래핑해야합니다.

= 는 양방향이므로 지시문 범위에서 변수를 변경하면 컨트롤러 범위 변수도 영향을받습니다.

& 는 컨트롤러 범위 메서드를 바인딩하는 데 사용되므로 필요한 경우 지시문에서 호출 할 수 있습니다.

여기서 장점은 변수의 이름이 컨트롤러 범위와 지시문 범위에서 동일 할 필요가 없다는 것입니다.

예를 들어, 지시문 범위에는 컨트롤러 범위의 "contVar"변수와 동기화되는 "dirVar"변수가 있습니다. 이는 한 컨트롤러가 변수 v1과 동기화 할 수있는 반면 동일한 지시문을 사용하는 다른 컨트롤러는 dirVar에 변수 v2와 동기화하도록 요청할 수 있으므로 지시문에 많은 힘과 일반화를 제공합니다.

다음은 사용 예입니다.

지시문과 컨트롤러는 다음과 같습니다.

 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
        }
    };
});

그리고 html (@ 및 =의 차이점에 유의하십시오) :

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

여기에 그것을 잘 설명하는 블로그 링크 가 있습니다.


간단히 우리는 다음을 사용할 수 있습니다.

  1. @ :-단방향 데이터 바인딩에 대한 문자열 값. 단방향 데이터 바인딩으로 범위 값을 지시문에 전달할 수 있습니다.

  2. = :-양방향 데이터 바인딩을위한 객체 값. 양방향 데이터 바인딩에서 지시문과 html에서도 범위 값을 변경할 수 있습니다.

  3. & :-메서드 및 함수용.

편집하다

우리의에서 구성 요소 에 대한 정의 각도 버전 1.5 이상
바인딩의 네 가지 유형이 있습니다 :

  1. = 양방향 데이터 바인딩 :-값을 변경하면 자동으로 업데이트됩니다.
  2. < 단방향 바인딩 :-부모 범위에서 매개 변수를 읽고 업데이트하지 않으려는 경우.

  3. @이것은 문자열 매개 변수 용입니다.

  4. &이것은 컴포넌트가 부모 범위에 무언가를 출력해야하는 경우 콜백위한 것입니다.


나는 그들 사이의 차이점을 보여주는 Angular 코드를 포함하는 작은 HTML 파일을 만들었습니다.

<!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')" <!-- scope: "=" -->
        attr2="VM.sayHi('Juan')" <!-- scope: "@" -->
        attr3="VM.sayHi('Juan')" <!-- scope: "&" -->
      ></a>
    </div>
    <script>
    angular.module("myApp", [])
    .controller("myCtrl", [function(){
      var vm = this;
      vm.sayHi = function(name){
        return ("Hey there, " + name);
      }
    }])
    .directive("myDir", [function(){
      return {
        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"
        }
      }
    }]);
    </script>
  </body>
</html>

= 방법은 바인딩 2 웨이 당신이 할 수 있습니다, 라이브 귀하의 지시어 내부 변경. 누군가가 해당 변수를 지시문에서 변경하면 지시문 내부에 변경된 데이터가 있지만 @ way는 양방향 바인딩 이 아닙니다 . Text 처럼 작동합니다 . 한 번 바인딩하면 그 값만 갖게됩니다.

더 명확하게 이해하기 위해이 훌륭한 기사를 사용할 수 있습니다.

AngularJS 지시어 범위 '@'및 '='


이 질문은 이미 맞았지만 다른 누군가가 AngularJS 범위라는 끔찍한 혼란으로 고군분투하는 경우를 대비하여 어쨌든 이것을 공유 할 것입니다. 이 의지 커버 =, <, @, &::. 전체 내용은 여기에서 확인할 수 있습니다 .


=양방향 바인딩을 설정합니다. 부모의 속성을 변경하면 자식도 변경되며 그 반대의 경우도 마찬가지입니다.


<단방향 바인딩, 부모와 자식을 설정합니다. 부모의 속성을 변경하면 자식도 변경되지만 자식 속성을 변경해도 부모 속성에는 영향을주지 않습니다.


@태그 속성의 문자열 값을 자식 속성에 할당합니다. 속성에 expression이 포함되어 있으면 표현식 이 다른 문자열로 평가 될 때마다 자식 속성이 업데이트됩니다. 예를 들면 :

<child-component description="The movie title is {{$ctrl.movie.title}}" />
bindings: {
    description: '@', 
}

여기서, description하위 범위의 속성은 표현의 현재 값 것 "The movie title is {{$ctrl.movie.title}}", movie상위 범위의 목적이다.


&약간 까다 롭고 실제로 그것을 사용하는 설득력있는 이유가없는 것 같습니다. 매개 변수를 하위 범위의 변수로 대체하여 상위 범위의 표현식을 평가할 수 있습니다. 예 ( plunk ) :

<child-component 
  foo = "myVar + $ctrl.parentVar + myOtherVar"
</child-component>
angular.module('heroApp').component('childComponent', {
  template: "<div>{{  $ctrl.parentFoo({myVar:5, myOtherVar:'xyz'})  }}</div>",
  bindings: {
    parentFoo: '&foo'
  }
});

주어진 parentVar=10경우 표현식 parentFoo({myVar:5, myOtherVar:'xyz'})은로 평가되고 5 + 10 + 'xyz'구성 요소는 다음과 같이 렌더링됩니다.

<div>15xyz</div>

이 복잡한 기능을 언제 사용하고 싶습니까? &사람들이 부모 범위의 콜백 함수를 자식 범위에 전달하는 데 자주 사용됩니다. 그러나 실제로는 '<'를 사용하여 함수를 전달하면 동일한 효과를 얻을 수 있습니다. 이는 더 간단하고 매개 변수 ( {myVar:5, myOtherVar:'xyz'}) 를 전달하는 어색한 중괄호 구문을 피합니다 . 중히 여기다:

다음을 사용한 콜백 &:

<child-component parent-foo="$ctrl.foo(bar)"/>
angular.module('heroApp').component('childComponent', {
  template: '<button ng-click="$ctrl.parentFoo({bar:'xyz'})">Call foo in parent</button>',
  bindings: {
    parentFoo: '&'
  }
});

다음을 사용한 콜백 <:

<child-component parent-foo="$ctrl.foo"/>
angular.module('heroApp').component('childComponent', {
  template: '<button ng-click="$ctrl.parentFoo('xyz')">Call foo in parent</button>',
  bindings: {
    parentFoo: '<'
  }
});

개체 (및 배열)는 복사되지 않고 자식 범위에 대한 참조로 전달됩니다. 이것이 의미하는 바는 단방향 바인딩이더라도 부모 및 자식 범위 모두에서 동일한 개체로 작업한다는 것입니다.


작동중인 다른 접두사를 보려면이 plunk를 엽니 다 .

1 회 바인딩 (초기화) 사용 ::

[공식 문서]
AngularJS의 이후 버전에서는 자식 범위 속성이 한 번만 업데이트되는 일회성 바인딩 옵션이 도입되었습니다. 이렇게하면 부모 속성을 볼 필요가 없어 성능이 향상됩니다. 구문은 위와 다릅니다. 일회성 바인딩을 선언 ::하려면 구성 요소 태그 의 표현식 앞에 추가합니다 .

<child-component 
  tagline = "::$ctrl.tagline">
</child-component>

이렇게하면 tagline단방향 또는 양방향 바인딩을 설정하지 않고 의 값이 자식 범위로 전파됩니다 . 참고 : tagline가 처음 undefined에 부모 범위에있는 경우 angular는 변경 될 때까지 감시 한 다음 자식 범위에서 해당 속성을 한 번 업데이트합니다.

요약

아래 표는 속성이 객체, 배열, 문자열 등인지 여부에 따라 접두사가 작동하는 방식을 보여줍니다.

다양한 격리 범위 바인딩이 작동하는 방식


@ local scope 속성은 지시문 외부에 정의 된 문자열 값에 액세스하는 데 사용됩니다.

= 외부 범위와 지시문의 격리 범위 사이에 양방향 바인딩을 만들어야하는 경우 = 문자를 사용할 수 있습니다.

& local scope 속성을 사용하면 지시문의 소비자가 지시문이 호출 할 수있는 함수를 전달할 수 있습니다.

아래 링크를 통해 예제를 통해 명확한 이해를하실 수 있습니다. 정말 유용하다고 생각해서 공유해 보시기 바랍니다.

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


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:

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.

<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

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.


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


the main difference between them is just

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

@ 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>.

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

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

<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


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.

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.

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 &

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


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


@는 로컬 / 지시적 범위 속성을 DOM 속성의 평가 된 값에 바인딩합니다. = 로컬 / 지시적 범위 속성을 부모 범위 속성에 바인딩합니다. & binding은 지시문 내에서 호출 될 수 있도록 지시문의 범위에 메소드를 전달하기위한 것입니다.

@ 속성 문자열 바인딩 = 양방향 모델 바인딩 및 콜백 메서드 바인딩

참고 URL : https://stackoverflow.com/questions/14050195/what-is-the-difference-between-and-in-directive-scope-in-angularjs

반응형