无法获取多个控制器中模型的内容AngularJS
希望,我的问题本身传达了我所期待的。 请详细说明文字 1.创建模块。无法获取多个控制器中模型的内容AngularJS
var ang = angular.module('myApp',[]);
- 我有一个名为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:
图片2:
在服务创建活动。 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);
}
]);
亲爱的朋友,你确定,这样它会工作,我不觉得,改变文件名到campaignService.js和新的campaignService.campaign(),将有所帮助, 你可以给一个jsfiddle演示,如果你可以 – 2014-10-01 12:32:18
@SAM:这个想法是在angularJs中使用依赖注入(DI)。这个例子很小,所以你不需要创建单独的js文件,否则你需要创建单独的模块,并使用DI来将服务与控制器绑定。这将帮助您实现与控制器逻辑分开的工厂方法。 – RahulB 2014-10-01 17:15:18
在角工厂我会提出一个不同的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);
});
任何希望被曝光出工厂根本就没有将其连接到运动物体。
如果你想要利用单身人士,请停止使用'new'。 – allenhwkim 2014-10-01 16:58:10