从一个控制器访问数据到另一个控制器 - AngularJS

时间:2018-01-06 05:51:32

标签: javascript arrays angularjs json object

addressbookController

$http({
        method: 'GET',
        url: '/api/getnewgroup'
    })
    .then(function (response) {
        $scope.draft.groups = response.data;
        $scope.groups = response.data; // updated
    }, function (response) {
        console.log(response);
    });

在上面的控制器中,我在 $ scope.draft.groups 中获得json响应,我在另一个名为 profsmsController的控制器中有 draft 对象

profsmsController

$scope.draft = {
            draftType: '',
            scheduledTime: '',
            senderdata: '',
            draftData: {
                contacts: ''
            },
            groups: {
                select: false
            },
            senderName: '',
            message: '',
            draftName: '',
            createdOn: '',
            updatedOn: ''
        };

如何访问$ scope对象?

我的控制器:

angular
    .module('sampleApp.controllers', [])

    //addressbook page controller
    .controller('addressbookCtrl', function ($http, $scope, $rootScope, $location,
        $state, toastr, $timeout, $window, sharedService) {

        // Groups

        // get group

        $http({
            method: 'GET',
            url: '/api/getnewgroup'
        })
        sharedService.getDraftPromise().then(function (response) {
            $scope.groups = response.data;
            $scope.draft.groups = response.data;
        }, function (response) {
            console.log('error');
        });

})



.controller('profsmsCtrl', function ($http, $scope, $rootScope, $location,
                $state, toastr, $timeout, $window) {



                /* for drafts */

                $scope.draft = {
                    draftType: '',
                    scheduledTime: '',
                    senderdata: '',
                    draftData: {
                        contacts: ''
                    },
                    groups: {
                        select: false
                    },
                    senderName: '',
                    message: '',
                    draftName: '',
                    createdOn: '',
                    updatedOn: ''
                };


                //add draft
                $scope.addmanualInputDraft = function () {
                    $http.post('/api/addmanualinputdraft', $scope.draft).then(function (response) {
                        toastr.success("Added successfully!");
                        $('.bd-example-modal-lg-manual').modal('hide');
                        $state.reload();
                    });
                }
        })

我的services.js:

angular
   .module('sampleApp.services', [])
   .factory('sharedService', function ($http) {

      var draftPromise = $http({
         method: 'GET',
         url: '/api/getnewgroup'
      });
      return {
         getDraftPromise: function () {
            return draftPromise;
         }
      };

   });

我的app.js:

'use strict';
angular
  .module('sampleApp', ['sampleApp.controllers', 'sampleApp.directives','sampleApp.services','sampleApp.filters','ui.router','toastr','ngSanitize', 'ui.select'])
  .config(function($stateProvider, $urlRouterProvider, $locationProvider) {

    $locationProvider.hashPrefix('');
    $urlRouterProvider.otherwise('/dash');
    $stateProvider
      .state('dash', {
        url: '/dash',
        templateUrl: 'partials/dash',
      })
      .state('quicksms', {
        url: '/quicksms',
        templateUrl: 'partials/quicksms',
        controller: 'quicksmsCtrl'
      })
      .state('professionalsms', {
        url: '/professionalsms',
        templateUrl: 'partials/professionalsms',
        controller: 'profsmsCtrl'
      })
      .state('file2sms', {
        url: '/file2sms',
        templateUrl: 'partials/file2sms',
        controller: 'file2smsCtrl'
      })
      .state('addressbook', {
        url: '/addressbook',
        templateUrl: 'partials/addressbook',
        controller: 'addressbookCtrl'
      })
  });

这是更新的完整代码。我想从地址簿控制器访问$ scope.draft.groups对象。

1 个答案:

答案 0 :(得分:2)

一般情况下,您需要创建一个包含共享数据的服务

myApp.factory('sharedService', function($http) {

    var draftPromise = $http({
        method: 'GET',
        url: '/api/getnewgroup'
    });

    return {
        getDraftPromise: function() {
            return draftPromise;
        }
    };
});

在您的控制器中,您可以通过将其声明为依赖项来使用该服务:

myApp.controller("myController", function($scope, sharedService) {

    sharedService.getDraftPromise().then(function(response) {
        $scope.draft.groups = response.data;
    });
});

两个控制器都将引用draftPromise的相同实例。

注意:如果您正在缩小代码,则需要使用备用注入使用数组的备用语法。看看official documentation for dependency injection