Do you communicate between two Angularjs directives?

advertisements

I am trying to communicate between two directives. I tried the service way, it didn't work. Maybe I am doing something wrong.

<list-data testing="trial" template-url="grid.html" link-passed="data.json"></list-data>

My directive and service:

app.directive('listData', function($http, serVice){
return {
    restrict: 'E',
    scope: {
        testing: '@',
        linkPassed: '@'
    },
    templateUrl: function(elem,attrs) {
        return attrs.templateUrl || 'some/path/default.html'
    },
    link: function($scope){
        var url = 'js/' + $scope.linkPassed;
        $http.get(url).then(success, error);

        function success(data){
            $scope.iconUrl = data.data;
        }

        function error(response){
            console.log(response)
        }

        $scope.tryingToClick = function(icon){
            serVice=icon.name;
            console.log(serVice)
        }
    }
};
});

app.directive('render', function(serVice){
    return {
        restrict: 'E',
        template: '{{rendering}}',
        link: function($scope){
            $scope.rendering = serVice.name;
            console.log(serVice)
        }
    };
});

app.factory('serVice', function(){
    return{items:{}};
})

grid.html is just a simple grid layout where I am trying to show the data in grid.

<div class="col-sm-6 grid" ng-repeat="icon in iconUrl">
<p ng-click="tryingToClick(icon)">{{icon.iconUrl}}</p>
</div>

I need to pass the data when I click the function tryingToClick and the icon passes to the render directive. I cannot use $rootscope here, nor make new controllers. I will be using the logic here in a pretty big enterprise app, just that I made a very simple version of it on my localhost, just to get the logic right.


Your service doesn't look quite right. I'd use

app.factory('serVice', function() {

  var settings = {};

  // optionally set any defaults here
  //settings.name = 'me';

  return settings;
});

and you're not setting the name property of the service here:

serVice=icon.name;

It should be

serVice.name = icon.name;

given that you're looking for the name property later: $scope.rendering = serVice.name;