【问题标题】:Not able to get the content of model in multiple controllers AngularJS无法在多个控制器AngularJS中获取模型的内容
【发布时间】:2014-11-26 06:29:20
【问题描述】:

希望,我的问题本身,传达了我正在寻找的东西。 会把话详细说 1. 创建模块。

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

  1. 我有一个名为 controller1 的控制器,其中包括“活动”工厂。

//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:

【问题讨论】:

  • 如果你想利用单例,请停止使用new

标签: javascript angularjs prototype-programming


【解决方案1】:

服务中创建广告系列。例如-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演示,如果可以的话
  • @SAM :想法是在 angularJs 中使用依赖注入(DI)。此示例很小,因此您无需创建单独的 js 文件,否则您需要创建单独的模块并使用 DI 将服务与控制器绑定。这将帮助您实现与控制器逻辑分开的工厂方法。
【解决方案2】:

在角度工厂中,我建议采用不同的方法。尽量不要将任何东西附加到对象的原型上。相反,您可以在角度工厂的范围内创建一个对象,将您想要的内容附加到它并返回它。例如:

     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);
});

任何你不想暴露在工厂之外的东西都不要附加到活动对象上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多