2016-11-16 110 views
0

我想其中的html看起來像這樣來創建一些種類的商店:Angularjs嵌套自定義指令

<body> 
    <main-wrapper> 

    <head> 
    </head> 

    <wrapper-one> 
     <products> 
     </products> 
    </wrapper-one> 

    <wrapper-two> 
     <log-in> 
     </log-in> 
    </wrapper-two> 

    </main-wrapper> 
</body> 

這種做法的一點是,我完全不使用控制器。只是指令。我想讓這些指令相互溝通。因此,讓我們說,當我登錄時,我想將每個產品從「綠色」改爲「藍色」。

這裏的指令:

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

return { 
      transclude:true, 
      restrict:'E', 
      template: '<div class="container" ng-transclude></div>', 
      controller : function($scope){ 
       this.addItem = function(val){ 
        console.log(val); 
       } 
      } 
     }; 
}); 

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

return { 
      restrict:'E', 
      transclude:true, 
      require : '^mainWrapper', 
      template: '<div class="col-sm-8" ng-transclude></div>', 
      controller : function($scope){ 
       this.addItem = function(val){ 
        console.log(val); 
       } 
      } 
     }; 
}); 

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

return { 
      restrict:'E', 
      require : '^wrapperOne', 
      templateUrl: 'view/products.html', 
      controller: function($scope, $element, $attrs) { 
       $scope.products = 
        [{product : 'car',color : 'green'}]; 
      } 
     }; 
}); 

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

return { 
      restrict:'E', 
      require : ['^wrapperTwo', '?products'], 
      scope: true, 
      link:function($scope,elem,attr,outerctrl){ 

      }, 
      templateUrl: 'view/login.html', 
      controller: function($scope) { 
      //login -> $scope.loggedIn = true 
      //logout -> $scope.loggedIn = false 
      } 
     }; 
}); 

我試圖使這個問題較短,所以我留下了一些代碼出於此。所以當用戶登錄和範圍loggedIn是真實的,我想改變產品的顏色。我一直在苦苦掙扎,現在只有很少的幫助。

我把這段代碼重新編譯到這裏,因爲我把它縮短了,並且改成了英文。我確信代碼中有一些拼寫錯誤,但不擔心它們。所有模板都可以工作,並且頁面看起來正確。

回答

0

我找到了解決辦法。在主包裝內我做到了這一點:

this.allProds = function (x) { 
    this.products = [{ product: "car", color: x}]; 

    return this.products; 
} 

現在我可以使用這個地方我想要的地方。來自產品指令的示例:

var products = outercontrol.allProds('blue');