Matt Boyle
Matt Boyle

Reputation: 385

passing scope to directive in angular js

I have the following Angular controller with a simple http get in it:

angular.module('SCtrl', ['ng-fusioncharts']).controller('SCtrl', function($scope, $http) {

    //Get All errors.
    $http({
        method: 'GET',
        url: 'node/errors'
    }).then(function successCallback(response) {
        $scope.notifications = response.data;
        console.log($scope.notifications);
    }, function errorCallback(response) {

    });
}

This works fine.

I then have the following directive. I want to be able to put {{notifications}} in the module body, however it doesn't work. I am guessing this is because I give the directive its own scope. What is the correct way to link scopes? My attempt is below but this doesn't work.

Thanks!

angular.module('SCtrl').directive('listDirective',function(){
    return{
        restrict:'E',
        scope:{
            listTitle:"@",
            notifications:"="
        },
        templateUrl: '../templates/listWidget.html',
        link: function(scope, element, attrs){
            $scope.notifications=scope.notifications;
        }
    }
});

Upvotes: 0

Views: 1475

Answers (2)

Manikandan Velayutham
Manikandan Velayutham

Reputation: 2228

<list-directive notifications="notifications"></list-directive>

link: function(scope, element, attrs){
            scope.notifications=scope.notifications;
        }

You should assign the values notifications="notifications" otherwise you can't get. Or else you can trigger API call in directive itself. Now you don't need to assign notifications="notifications".

Upvotes: 0

Thalaivar
Thalaivar

Reputation: 23622

Mis uderstood initially, as @devqon pointed out, you need to pass your notification object in list-directive which can be accessed in your listWidget.html

<list-directive notifications="notifications"></list-directive>

Upvotes: 2

Related Questions