2013-08-12 3 views
0

jsbin : http://jsbin.com/oworoz/1/editAngular.js - 지침 및 서비스 통신

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> 
     <meta charset=utf-8 /> 
     <title>JS Bin</title> 
    </head> 
    <body ng-app="deeme"> 
     <modal ></modal> 
     <script type="text/ng-template" id="templ1" >Bu birinci template</script> 
     <script type="text/ng-template" id="templ2" >Bu ikinci template</script> 
     <script type="text/ng-template" id="templ3" >Bu üçüncü template</script> 

     <button ng-controller="b1" ng-click="update()">templ1</button> 
     <button ng-controller="b2" ng-click="update()">templ2</button> 
     <button ng-controller="b3" ng-click="update()">templ3</button> 

     <script type="text/javascript"> 
      angular.module ("deeme", []) 
      .factory("serv", function(){ 
       return { 
        data: { 
         template: "templ1" 
        } 
       } 

      }) 
      .controller("b1", ["$scope", "serv", function($scope, serv){ 
       $scope.update = function(){ 
        serv.data.template = "templ1"; 
       } 
      }]) 
      .controller("b2", ["$scope", "serv", function($scope, serv){ 
       $scope.update = function(){ 
        serv.data.template = "templ2"; 
       } 
      }]) 
      .controller("b3", ["$scope", "serv", function($scope, serv){ 
       $scope.update = function(){ 
        serv.data.template = "templ3"; 
       } 
      }]) 
      .directive("modal", ["serv", function(serv){ 
       return { 
        restrict: "E", 
        template: "<div ng-include='currTempl'></div>", 
        replace: true, 
        link: ["$scope", function($scope){ 
         $scope.currTempl = serv.data.template; 
         alert($scope.currTempl); 
         $scope.$watch(serv.data.template, function(newVal, oldVal){ 
          $scope.currTempl = newVal; 
         }); 
        }] 
       } 
      }]) 
     </script> 
    </body> 
</html> 

내가 다른 템플릿에 다른 단추를 클릭 할 때마다 표시됩니다 모달 같은 용기를 만들기 위해 노력하고있어. 이것을 달성하기 위해 필자는 세 개의 버튼과 컨트롤러 컨트롤러를 만들었습니다. 서비스에서 제공하는 공유 변수와 공유 변수를 읽는 지시문을 업데이트하고 공유 변수의 값에 따라 지정된 요소의 내용을 변경합니다 .

그러나 나는 지시어를 작동시킬 수 없었다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

1

$ 시계는 필요하지 않습니다. 그냥 serv.data에 지시 범위 속성을 할당합니다

.directive("modal", function(serv){ 
    return { 
     restrict: "E", 
     template: "<div ng-include='data.template'></div>", 
     replace: true, 
     link: function($scope){ 
      $scope.data = serv.data; 
     } 
    } 
}) 

당신의 컨트롤러가 서비스 속성을 업데이트 할 때-포함 NG는 알 수 있습니다.