Anthony Akpan
Anthony Akpan

Reputation: 73

Passing Data from a service to a directive in AngularJs

here my code for the directive

app.directive('studentlist',function(){
return{
    restrict:'E',
    scope: {},
    templateUrl:'js/directives/studentList.html'
};

});

and here's the code for my service

app.factory('students',['$http',function($http){
return $http.get('http://localhost/database2/php/students.php')
    .success(function(data){
        return data;
    })
    .error(function(err){
        return err;
    });

}]);

heres a snippet of my HTML

<div ng-repeat="student in studentList" class="row border">
        <studentList info="{{ students.info }}"></studentlist>
</div>

I need to know how to pass the data from the service to the directive. so it shows up in the tag

Upvotes: 0

Views: 850

Answers (1)

Peter Ashwell
Peter Ashwell

Reputation: 4302

app.directive('studentlist',function(students){
return{
    restrict:'E',
    scope: {},
    link: function(scope) {
      students.then(data) {
        console.log('putting "students" on scope!:', data);
        scope.students = data;
      };
    },
    templateUrl:'js/directives/studentList.html'
};

Not sure what your JSON looks like, but your directive should eventually have access to the students blob. Try putting {{students}} in the studentList directive template.

... and you don't need the binding in the directive attributes anymore.

<div ng-repeat="student in studentList" class="row border">
        <studentList></studentlist>
</div>

Upvotes: 1

Related Questions