2014-12-30 4 views
0

읽기에서 Scopes (Part 2 of the AngularJS - from beginner to expert in 7 steps series) : A $scope에는보기에서 사용 가능한 데이터와 기능이 모두 포함될 수 있습니다. AngularJS가 로컬 $scope에서 기능을 찾을 수 없으면 포함하는 (부모) $scope이 거기에있는 속성이나 메소드를 검사합니다.

위의 코드에서
compile: function(tElement, tAttrs) { 

    var contents = tElement.contents().remove(); 
    console.log(contents); 
    var compiledContents; 

    // postLink function. 
    return { 
     post: function(scope, iElement, iAttrs) { 
      if (!compiledContents) { 
       // Get linking function. 
       compiledContents = $compile(contents); 
      } 

      // Link scope and the template together. 
      compiledContents(scope, function(clone) { 
       iElement.append(clone); 
      }); 

      scope.myEvent = function() { 
       console.log("My Event handled!"); 
      }; 
     }, 
     pre: function(scope, iElement, iAttrs) { } 
    } 
} 

, 내가 인스턴스 요소$scope에 기능을 장착 한이 성공적으로 호출됩니다

이 지침의 컴파일 기능의 내 구현을 감안할 때 (Angularjs: understanding a recursive directive 기준) 보기에서. 그러나 나는 예를 요소 범위와에 함수 정의를 이동 할 수있을 것으로 예상 부모 컨트롤러의 $scope : 부모 컨트롤러의 기능은 (는) 지침의 부모는 비록 호출되지 않습니다 그러나

angular.module('Myapp').controller('MyParentController', ['$scope', 
     function($scope) { 
      $scope.myEvent = function() { 
        console.log("My Event handled!"); 
      }; 
}]); 

컴파일의 자체 구현을 제공했습니다.

angular.module('Myapp').directive("my-directive", function(RecursionHelper) { 
    return { 
     restrict: "E", 
     scope: { 
      data: '=data' 
     }, 
     templateUrl: 'view.html', 
     compile: function(tElement, tAttributes) { 
      return RecursionHelper.compile(tElement, tAttributes); 
     } 
    }; 
}); 

.. 그리고 RecursionHelper :

는 지시어에 대한 코드를 추가하는 업데이트 당신의 지시가 고립 범위가

angular.module('Myapp').factory('RecursionHelper', 
    ['$compile', 
    function($compile) { 
     var RecursionHelper = { 
      compile: function(tElement, tAttrs) { 

       var contents = tElement.contents().remove(); 
       var compiledContents; 

       return { 
        post: function(scope, iElement, iAttrs) { 
         if (!compiledContents) { 
          compiledContents = $compile(contents); 
         } 

         compiledContents(scope, function(clone) { 
          iElement.append(clone); 
         }); 
        }, 
        pre: function(scope, iElement, iAttrs) { } 
       } 
      } 
     } 
     return RecursionHelper; 
    }]); 
+0

전체 지시문 코드 – harishr

+0

을 공유 할 수 있습니까? @HarishR - OP는 전체 지시문 코드를 포함하도록 업데이트되었습니다. – Jack

+0

은'ng-click'을 통해 호출되는'$ scope.myEvent'입니까? pls 당신의 지시어의 템플릿을 여기에 붙일 수 있습니까? – elaijuh

답변

0

변화

당신의 지침 변화에 다음
scope: { 
     data: '=data' 
     myEvent: '=myEvent' 
    } 

 angular.module('Myapp').directive("my-directive", 

에 angular.module ('MYAPP'). 지침 ("myDirective"

을 당신의 범위

다음 함수를

과 같이 전달하십시오.
<my-directive data="scope-data" my-event="scope-event-function()"></my-directive> 
0

때문에, 당신은 단지 부모 범위에 data에 액세스 할 수 있습니다.

scope: { 
    data: '=data' 
}, 
관련 문제