我知道我不是第一個有這個問題但沒有解決方案在這裏幫助我解決它。
我有兩個控制器一個ShowController和一個CreateController。我想從ShowController廣播並在CreateCrontroller中接收。爲此,我正在使用BroadcastService。一切都按預期工作。由於點擊事件,ShowController將數據保存到服務廣播事件,並且CreateController接收事件和數據。根據我想要激活選項卡的數據,可以使用由CreateController啓動的視圖。在on方法中設置$ scope變量後,它們正在更改,但視圖不會自行更新。
我試圖包裝$廣播,以及$的方法在$時間戳強制$應用。我也在$ scope變量被設置後嘗試了$ apply,並且試圖在$ apply中的一個匿名函數中設置$ scope變量。非這些解決方案爲我工作。我明顯錯過了一些東西。
編輯 附加的fiddle正在工作,但沒有問題。兩個控制器都有一個父控制器。如果我在子控制器中檢查$scope
,新數據將被添加,但是如果我檢查父控制器$$childTail
,並且子數據沒有更改。所以廣播是有效的。問題在控制器結構或範圍繼承內。
爲什麼視圖監聽父控制器,即使變量未在父控制器中啓動和更改?
編輯2 據我試圖找到問題,我想我找到了一個問題。如果我嘗試從show controller廣播到創建控制器。創建控制器尚未初始化。在我嘗試第二次廣播之後。但仍然變量不會在視圖中改變!看到這個工作plnkr分析問題。我嘗試通過廣播將節目更改爲創建控制器。如果您在創建控制器中檢查範圍,則該變量會更改,但在父範圍中則不會。
angular.module('module.service')
.factory('SharedFactory',['$rootScope', '$timeout', function ($rootScope, $timeout) {
var sharedService = {};
sharedService.message = '';
sharedService.data = {};
sharedService.prepForBroadcast = function(event, data) {
this.event = event;
this.data = data;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$timeout(function() {$rootScope.$broadcast('updateShared');});
};
return sharedService;
}]);
// controller 1
$scope.functionName = function(data) {
// tried this as well with and without the $timeout
$timeout(function() {
SharedFactory.prepForBroadcast('bookResources', {data:data});
}, 0);
// ui-router changes state/view
$timeout(function() {
$state.go('create');
}, 1);
};
// controller 2
$rootScope.$on('updateShared', function() {
// first attempt
$timeout(function() {
$scope.variable.data = SharedFactory.data; // updating in controller but not in view
}, 100);
// seconde attempt
$scope.$apply(function() {
$scope.variable.data = SharedFactory.data; // updating in controller but not in view
});
});
<ol>
<li data-ng-repeat="phase in array">
<span data-ng-repeat="com in phase.array">{{com.type}}
<span data-ng-click="functionName(phase)"> {{com.var1}}/{{com.var1}}
</span>
</span>
</li>
</ol>
你可以顯示標記嗎? – 2015-02-06 10:46:34
我更新了小提琴和代碼。這可能是父母和孩子範圍的問題嗎?爲了避免這種情況,我在on方法中設置對象的屬性而不是對象或數組本身。 – 2015-02-06 10:53:55
請創建一個工作小提琴來幫助我們:) – DonJuwe 2015-02-06 11:47:55