AngularJS Load Data from Service

前端 未结 3 1727
[愿得一人]
[愿得一人] 2020-12-02 14:41

I am having a problem getting data from a service populated into my view. I have a service defined as such

app.factory(\'nukeService\', function($rootScope,          


        
3条回答
  •  自闭症患者
    2020-12-02 15:42

    What I do is that I expose the data straight from the service, and have a method which initializes this data. What is wrong with this?

    Service:

    app.factory('nukeService', function($scope, $http) {
        var data = {};
        data.nukes = [];
    
        //Gets the list of nuclear weapons
        var getNukes = function() {
            $http.get('nukes/nukes.json').success(function(data) {
                    data.nukes = data;
            });
        };
    
        // Fill the list with actual nukes, async why not.
        getNukes();
    
        return {
            data : data
            // expose more functions or data if you want
        };
    });
    

    Controller:

    function NavigationCtrl($scope, nukeService){
         $scope.data = nukeService.data;
         //then refer to nukes list as `$scope.data.nukes`
    }
    

提交回复
热议问题