1

I am trying to use promises to tidy up my Angular code a bit. When I enter a callback function (success or error) however. My scope is gone. The $scope, service and object are all null inside the callback.

The variable vm is still known though.

Any ideas on how I can fix this?

(function (app) {
'use strict';
var MyController = (function () {
    function MyController($scope, aService, anotherService) {
        var vm = {
            loaded: false,
            anObjToInstantiate: null,
            error: null
        };

        aService.makeAServiceCall()
            .success(function (result) {
                vm.anObjToInstantiate = result.data;
                anotherService.notifySomething(); /* Null! */
                vm.loaded = true;
            })
            .error(_handleError);

        function _handleError(error) {
            vm.error = error;
        }

        return vm;
    };

    MyController.$inject = ['$scope', 'AService', 'AnotherService'];
    return MyController;
}());

app.controller('MyController', MyController);

}(angular.module('app.amodule')));
Jente Rosseel
  • 1,195
  • 1
  • 10
  • 18

1 Answers1

1

You controller is wrongly defined. It shouldn't return anything. All it does is play with scope variable and services.

Controller

(function(app) {
    'use strict';
    var MyController = function($scope, aService, anotherService) {
        $scope.vm = {
            loaded: false,
            anObjToInstantiate: null,
            error: null
        };

        aService.makeAServiceCall()
            .success(function(result) {
                $scope.vm.anObjToInstantiate = result.data;
                anotherService.notifySomething(); /* Null! */
                $scope.vm.loaded = true;
            })
            .error(_handleError);

        function _handleError(error) {
            $scope.vm.error = error;
        }
    };

    MyController.$inject = ['$scope', 'AService', 'AnotherService'];
}());

app.controller('MyController', MyController);

}(angular.module('app.amodule')));

For ControllerAs It would like below

Controller(ControllerAs)

(function(app) {
    'use strict';
    var MyController = function($scope, aService, anotherService) {
        var ctrl = this;
        ctrl.vm = {
            loaded: false,
            anObjToInstantiate: null,
            error: null
        };

        aService.makeAServiceCall()
            .success(function(result) {
                ctrl.vm.anObjToInstantiate = result.data;
                anotherService.notifySomething(); /* Null! */
                ctrl.vm.loaded = true;
            })
            .error(_handleError);

        function _handleError(error) {
            ctrl.vm.error = error;
        }
    };

    MyController.$inject = ['$scope', 'AService', 'AnotherService'];
}());
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299