0
<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

3
  • Possible duplicate of AngularJS factory http returns empty Commented Jun 25, 2016 at 3:21
  • i think you should use a $promise to bind the object. Commented Jun 25, 2016 at 3:34
  • Ok, it works outside but $scope.wp is an $$state : Object. How can I access the data Commented Jun 25, 2016 at 3:41

1 Answer 1

1

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.

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

2 Comments

$scope.wp can recieve data that I want but It doesn still bind data to ng-model
Try assigning $scope.wp = {} before you call your provider. Your last console.log will still be empty though because it runs before your promise resolves. Also, if it's still not working then post your template.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.