2

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

In this above controller, i am getting json response in $scope.draft.groups, I have this draft object in another controller called profsmsController.

profsmsController :

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

How to access $scope object ?

My Controller:

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

My services.js:

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

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

   });

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

This is updated full code. I want to access $scope.draft.groups object from addressbook Controller.

3
  • Create service which will be responsible for sharing a data amongst different component of your application Commented Jan 6, 2018 at 5:58
  • I dont know to create a service, will you share some piece of code? i will learn from this. Commented Jan 6, 2018 at 5:58
  • I'd recommend to go over this answer. Commented Jan 6, 2018 at 6:01

1 Answer 1

2

In general, you'd want to create a service that holds your shared data:

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

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

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

In your controllers, you can then use the service by declaring it as a dependency:

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

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

Both controllers will refer to the same instance of draftPromise.

Note: if you are minifying your code, you'll want to use the alternate syntax for dependency injection that uses arrays. Take a look at the official documentation for dependency injection.

Sign up to request clarification or add additional context in comments.

5 Comments

Take a look at updated answer -- you have to declare sharedService as a dependency in your controllers
If you're using minified code, you'll want to use the syntax of dependency injection that uses an array like so: myApp.controller("myController", ["$scope", "sharedService", function($scope, sharedService) { ... }]);. Otherwise, your controller will not recognize $scope or sharedService when the code is minified
thats not the problem , see my draft object, I have group inside my draft object. See my response i am storing that response in $scope.draft.groups, but in this It only taking $scope.draft and throwing console as "TypeError: Cannot set property 'groups' of undefined".
You'll need to make sure that $scope.draft is defined before setting $scope.draft.groups. You can do something like: $scope.draft = { groups: response.data }, which will define $scope.draft and $scope.draft.groups in the same statement.
Seems like there might be a bug somewhere -- are you able to post full code of the controller?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.