2016-01-16 62 views
1

我試圖在控制器和指令之間進行通信。我研究過很少的博客並搜索過計算器,關於這些主題有一些很棒的概念。但他們都是案件特定的問題。我試圖用他們的風格解決我的問題,但我發現沒有運氣。從主html頁面控制器發送數據到指令控制器

我的問題是..我需要發送一些數組到一個指令。該數組在主html文件的控制器中定義。而且html頁面也有一個指令。該指令還有他自己的控制器來完成一些工作。我需要向該指令控制器發送一個數組進行處理,並且該數組必須是雙向綁定的,以便一側的任何更改都可以反映在另一側。

+0

當你打電話給你的指令 –

+0

您可以發佈您的代碼使用屬性或通過互聯網的任何調查結果 –

+0

我建議你閱讀這篇博文.http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/ – katmanco

回答

1

我對付這種情況近來並想出一個辦法來解決它。 您可以使用此過程發送數據並在來自控制器的指令中對其進行處理。 首先要在主要頁面控制器和像你想定義一些陣列...

app.controller("ctrl", function($scope) { 
    $scope.scope = $scope; //this is to transfer the current scope to the directive 
    $scope.array = [{ 
     "a": "vfdxvf", 
     "b": "sdc" 
    }, { 
     "a": "vfdxvf", 
     "b": "sdc" 
    }, { 
     "a": "vfdxvf", 
     "b": "sdc" 
    }, { 
     "a": "vfdxvf", 
     "b": "sdc" 
    }]; 
}); 

在上面的代碼中,$ scope.scope = $範圍是創建控制器範圍的參考。

然後像這樣定義指令。它會綁定你想要的所有值。任何一方陣列的任何變化也會反映在另一方面。

這裏是一個僞代碼..

app.directive("someDirective", function() { 
    return { 
     restrict: "EA", 
     scope { 
      array: "=", // two way binding of array.. 
      scope: '=' // collecting the scope of the controller it came from 
     }, 
     templateUrl: "./templates/test.html", 
     controller: function($scope) { 
      $scope.newArray = $scope.scope.array; 
      //do useful coding with the array... 
     } 
    } 
}); 

以及用於在HTML主頁只寫這樣的..

<some-directive scope="scope" array="array"></some-directive>