Zeus Ken
Zeus Ken

Reputation: 49

$scope not able to get data from factory using $http.get in Angularjs

<script>
var app = angular.module('myApp', ['ngMaterial']);

app.factory('factoryProvider', function ($http, $q) {
    var facObj = {};
    facObj.getLastWorkplace = $http.get('plugins/wcf-service/ServiceProvider.svc/getLastWorkPlacesJSON')
        .then(function (response) {
            return response.data;
        });
    return facObj;
});

app.controller('dashboardController', function ($scope, factoryProvider) {

    factoryProvider.getLastWorkplace.then(function (successResponse) {
        $scope.wp = successResponse;
        console.log('inside');
        console.log($scope.wp); // Return an object that I want
    });
    console.log('outside');
    console.log($scope.wp); // $scope.wp is empty
});

The outside console log runs first, inside console log is the second. The problem is that $scope.wp can just get data in getLastWorkplace callback functions and it can not bind data to ng-model(using wp.property). How to solve it? Thanks for your reading

Upvotes: 0

Views: 59

Answers (1)

Rob
Rob

Reputation: 12872

You are assigning $scope.wp twice and the final assignment is the return value of your getLastWorkplace call (which you aren't returning anything.)

Change it to this...

factoryProvider.getLastWorkplace.then(function (successResponse) {
    $scope.wp = successResponse;
});

or...

$scope.wp = factoryProvider.getLastWorkplace;

but not both.

Upvotes: 1

Related Questions