AngularJS: How to load JSON data onto a scope variable

后端 未结 5 1457
南笙
南笙 2021-02-07 21:46

I\'m creating a personal website where I can keep updating content without having to manipulate the HTML. I\'m trying to achieve this by simply loading and updating

5条回答
  •  执念已碎
    2021-02-07 22:19

    Modified Your Method Use this and Check output.

    var myapp=angular.module('mainApp',[]);
    myapp.controller('mainController',function($scope,$http){
        $scope.content = null;
        $http.get('urlpath'}).
            success(function(data, status, headers, config) {
                $scope.contents=data;
            }).error(function(data, status, headers, config) {          
        });
    });
    

    or Another Good Practice I see

    Use Factory Service Method:-

    angular.module('mainApp').factory('Myservice', function($http){
        return {
            getdata: function(){
                  return $http.get('url'); // You Have to give Correct Url either Local path or api etc 
    
            }
        };
    });
    

    Inject above service to Controller

    Controller :-

    angular.module('mainApp',[]).controller('mainController',function($scope,Myservice){
            $scope.content = null;
             Myservice.getdata().success(function (data){
                           alert('Success');
                       $scope.content=data[0]; // as per  emilySmitley Answer which is Working Good
    
                     });
        });
    

    Let Me Know if You have any Questions . Good Luck

提交回复
热议问题