0

I'm trying to develop a directive that has it's own controller so it can collect the data it need's from the API and be injected anywhere.

Here's what I got so far:

(function () {
'use strict';

angular
    .module('app.hostelsmg.bookings')
    .directive('bookingsChart', bookingsChart);

function bookingsChart() {
    return {
        restrict: 'E',
        scope: true,
        controller: [function(){
            $scope.test = 'Hi there!';
        }],
        compile: function(tElem, attrs){
            tElem.html('{{test}}');
            return function(scope, elems, attrs){

            }
        }
     }
 }
})();

So what I'd like, is the directive to get data from it's own controller. So far I couldn't get it to work that way.

Does anyone know how?

1
  • Your code should work fine. Just inject $scope in your controller, and then use the variables assigned to $scope in your template directly. Commented Jan 28, 2017 at 4:52

1 Answer 1

1

You can use something like this

function bookingsChart() {
    return {
        restrict: 'E',
        scope: true,
        controller: ['$scope', 'yourservice', function ($scope, yourservice) {
            $scope.data = [];   //bind this data to your view

            $scope.getServiceData = function (count) {
                //your service call
                yourservice.getServiceData(count).then(function (data) {
                    $scope.data = data;  //sets data in $scope.data variable
                });
            }
        }],
        link: function (scope, elements, attributes) {
            //if you want to pass any parameters from your UI to your service method
            scope.getServiceData(attributes.count);    //calls the getServiceData in controller defined above 
        }
     }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.