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

前端 未结 3 922
傲寒
傲寒 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:33

    As you say, you don't need to request the file twice. Pass it from your controller to your directive. Assuming you use the directive inside the scope of the controller:

    .controller('MyController', ['$scope', '$http', function($scope, $http) {
      $http.get('locations/locations.json').success(function(data) {
          $scope.locations = data;
      });
    }
    

    Then in your HTML (where you call upon the directive).
    Note: locations is a reference to your controllers $scope.locations.

    And finally in your directive

    ...
    scope: {
      locationData: '=locationData'
    },
    controller: ['$scope', function($scope){
      // And here you can access your data
      $scope.locationData
    }]
    ...
    

    This is just an outline to point you in the right direction, so it's incomplete and not tested.

提交回复
热议问题