0
var foo = angular.module('foo', []);

foo.factory('apiService', function($http){
    'use strict';

    return {
        getItems: function() {
            return $http.get('api/get-items')
                .then(function(result) {
                    return result;
                });
        }
    };
});

OutlastApp.controller('ItemListCtrl', function ($scope, apiService) {
    'use strict';

    apiService.getItems().then(function(result) {
        $scope.items = result.data;
    });
});

OutlastApp.controller('AddItemCtrl', function ($scope, $http, $rootScope, apiService) {
    'use strict';

    ...

    $scope.saveItem = function(item) {
        $http({
            url: 'api/add-item',
            method: 'GET',
            params: {
                name: item.name,
                description: item.description,
                ...
            }
        }).success(function(data, status, headers, config) {
            // TODO: What to do?
        });
    };
});

As you can seem, I have setup $scope.items to get its contents from an AJAX call.

What I am trying to accomplish is that I want to try to update the $scope.items so that it will reflect the newly added item.

How do I do this? Is this the correct way to do some sort a two-way binding between API and scope variables?

1 Answer 1

3

Given what I can see here you need to probably share the "items" collection between the two controllers. In order to do this you can use a factory to store the items collection (approximately):

app.factory('SharedDataService', function () {
    return {
        items: []
    };
});

After you have created this you can use inject it into both controllers and the "items" object will be shared between them. Then you can just push the new item after it is saved:

$http({
    // run your call here
}).success(function(data, status, headers, config) {
    // Here is where you push the new/saved item into the shared data:
    SharedDataService.items.push(item);
});

That should really do it. Best of luck!

Video Tutorial - In case you haven't seen this concept before - as of now - John Lindquist has an excellent video tutorial here.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.