In Angular, how to pass JSON object/array into directive?

前端 未结 3 930
傲寒
傲寒 2020-12-07 10:01

Currently, my app has a controller that takes in a JSON file then iterates through them using \"ng-repeat\". This is all working great, but I also have a directive that need

3条回答
  •  爱一瞬间的悲伤
    2020-12-07 10:21

    What you need is properly a service:

    .factory('DataLayer', ['$http',
    
        function($http) {
    
            var factory = {};
            var locations;
    
            factory.getLocations = function(success) {
                if(locations){
                    success(locations);
                    return;
                }
                $http.get('locations/locations.json').success(function(data) {
                    locations = data;
                    success(locations);
                });
            };
    
            return factory;
        }
    ]);
    

    The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

    Use this service DataLayer in your controller and directive is ok as following:

    appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
        DataLayer.getLocations(function(data){
            $scope.locations = data;
        });
    });
    
    .directive('map', function(DataLayer) {
        return {
            restrict: 'E',
            replace: true,
            template: '
    ', link: function(scope, element, attrs) { DataLayer.getLocations(function(data) { angular.forEach(data, function(location, key){ //do something }); }); } }; });

提交回复
热议问题