2015-07-10 71 views
0

我在2個控制器和2個視圖之間共享數據時遇到問題。我有2個意見。我創建了2個獨立的控制器並綁定了2個不同的視圖。現在我有2個控制器之間的2個共享數據,所以我創建了一個服務。問題是一個控制器從遠程源獲取數據,而其他控制器正在使用該數據。但是消費數據的視圖首先加載,因此從遠程源獲取的數據不會被第一個數據完全利用。例如。AngularJS兩個控制器之間的數據共享

//My Services 
as.service('songGenreService', function() { 
    var genreList = []; 

    var addGenres = function (newObj) { 
     genreList = newObj; 
    }; 

    var getGenres = function() { 
     return genreList; 
    }; 

    return { 
     addGenres: addGenres, 
     getGenres: getGenres 
    }; 
}); 


as.controller('SongListController', ['$scope', 'Song', "$stateParams", 'Category', 'Album', 'base64', 'langConversion', 'CONFIG', 'Poet', "songGenreService", 
    function ($scope, Song, $stateParams, Category, Album, base64, langConversion, CONFIG, Poet, songGenreService) {   

     $scope.getCategories = function() { 
      Category.find({ 
       filter: { 
        fields: ["id", "name"], 
        where: { 
         parentId: 2 
        } 
       } 
      }).$promise.then(function (categories) { 

       $scope.categories = categories;// Here I am giving data to other source. 
       songGenreService.addGenres(categories); 

       $scope.genreId = $scope.categories[0].id; 
       $scope.genreName = $scope.categories[0].name; 
      }); 
     }(); 
} 
]); 

as.controller('SongGenreController', ['$scope', 'Song', "songGenreService", 
    function ($scope, Song, songGenreService) { 
     $scope.categories = songGenreService.getGenres(); 
     console.log($scope.categories); 
    } 
]); 

問題是「SongGenreController」首先加載,因爲它首先加載HTML。我希望在數據加載成功時填充它。 「songGenreService.getGenres();」不與遠程源運行。

回答

1

我修復類似問題的方法是使用發佈訂閱機制。 在你的服務,你可以把一個類型時添加像這樣公佈:

var addGenres = function (newObj) { 
     genreList = newObj; 
     $rootScope.$broadcast('genresUpdated, genreList); 
    }; 

然後在兩個控制器你訂閱事件:

$scope.$on('genresUpdated', function(event, genreList){ 
    $scope.genres = genreList; 
    // and other code you want to have triggered when the genreList changes 
}); 
+0

'$範圍$ on'我要把它添加到第二個控制器,從第一個控制器提取數據。對?還是在兩個控制器? – Sankalp

+0

我會將此添加到兩個控制器。 –

+0

你可以這樣看待它。您的服務是父母,他擁有所有數據。您的控制器是孩子,他們需要這些數據,以便控制器給他們一份副本,以便他們可以將其存儲在本地範圍內。但是當他們通過調用父添加方法添加某些內容時,他們也希望他們的本地副本保持最新狀態。所以他們認同父母的變化。該服務反過來進行發佈以在數據發生變化時通知孩子 –

相關問題