2014-10-01 56 views
0

希望,我的問題本身傳達了我所期待的。 請詳細說明文字 1.創建模塊。無法獲取多個控制器中模型的內容AngularJS

var ang = angular.module('myApp',[]);

  1. 我有一個名爲controller1的控制器,幷包含'campaign'工廠。

//controllerone.js

ang.controller('controller1', function(campaign){ 
    $scope.campaigns = new campaign(); 
    //Here the whole campaign object is displayed with data, refer the Image 1 attached 
    console.log($scope.campaigns); 
}); 
ang.factory('campaign', function($http){ 
    var campaign = function(){ 
    this.timePeriodList = buildTimePeriodList(); 
    ... 
    ... 
    this.campaignList = []; 

}; 
Campaigns.prototype.fetchCampaigns = function() { 
    //Some service call to load the data in this.campaignList 
}; 
}); 

現在試圖調用同一個廣告活動廠第二控制器,只得到對象結構,沒有得到數據。

//controlertwo.js

ang.controller('controller2', function(campaign){ 
    $scope.campaigns = new campaign(); 
    //Here only the campaign object structure is displayed, but no data for campaignList, ref image 2 attached 
    console.log($scope.campaigns); 
}); 

以來,工廠服務是一個單獨的對象,我期待了同樣的結果,因爲我在controllerone.js了,

圖片1:

Image 1

圖片2:

Image 2

+0

如果你想要利用單身人士,請停止使用'new'。 – allenhwkim 2014-10-01 16:58:10

回答

0

服務創建活動。 EG-CampaignService會

更新後的代碼---

var ang = angular.module('myApp', []); 

ang.service('campaignService', function($scope){ 
    var campaign = function(){ 
    this.timePeriodList = buildTimePeriodList(); 
    ... 
    ... 
    this.campaignList = []; 
    } 
    return campaign; 
}); 

ang.controller("controller1", ["campaignService", 
function($scope, $rootScope, campaignService){ 
    $scope.campaigns=campaignService.campaign(); 
} 
]); 

ang.controller("controller2", ["campaignService", 
function($scope, $rootScope, campaignService){ 
    $scope.campaigns=campaignService.campaign(); 
    console.log($scope.campaigns); 
} 
]); 
+0

親愛的朋友,你確定,這樣它會工作,我不覺得,改變文件名到campaignService.js和新的campaignService.campaign(),將有所幫助, 你可以給一個jsfiddle演示,如果你可以 – 2014-10-01 12:32:18

+0

@SAM:這個想法是在angularJs中使用依賴注入(DI)。這個例子很小,所以你不需要創建單獨的js文件,否則你需要創建單獨的模塊,並使用DI來將服務與控制器綁定。這將幫助您實現與控制器邏輯分開的工廠方法。 – RahulB 2014-10-01 17:15:18

0

在角工廠我會提出一個不同的approach.Try不附加任何一個對象的原型。相反,您可以在角廠的範圍內創建一個對象,附上您想要的內容並將其返回。例如:

 ang.factory('campaign', function ($http) { 
var campaign = {}; 
campaign.method1 = function() { 
    //.. 
} 
campaign.campaignList = []; 
//... 

campaign.fetchCampaigns = function() { 
    //Some service call to load the data in this.campaignList 
}; 

});

//不是在您的控制器如果活動被注入就可以使用這種方式:你不

ang.controller('controller2', function (campaign) { 
    campaign.fetchCampaigns();// This will fill the list and it will remain filled when other controllers use this factory... 
    console.log(compaign.campaignList); 
}); 

任何希望被曝光出工廠根本就沒有將其連接到運動物體。

相關問題