2017-03-01 92 views
0

我正试图在两个指令之间进行通信。我尝试了服务方式,但没有奏效。也许我做错了什么。在两个指令Angularjs之间进行通信?

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

我的指导和服务:

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就是在那里我试图显示网格中的数据一个简单的网格布局。

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

当我单击函数tryingToClick并将图标传递给render指令时,我需要传递数据。我不能在这里使用$ rootcope,也不能创建新的控制器。我将在一个相当大的企业应用程序中使用这里的逻辑,只是为了让逻辑正确,我在本地主机上做了一个非常简单的版本。

回答

0

您的服务看起来不太正确。我会用

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

    var settings = {}; 

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

    return settings; 
}); 

,你就不是在这里设置服务的名称属性:

serVice=icon.name; 

应该

serVice.name = icon.name; 

因为你要找的name property later:$scope.rendering = serVice.name;

0

你是什么意思不创建更多的控制器?你的意思是你不能在应用上创建更多的内容,或者你不能在指令中使用控制器?

从我明白你的问题我一起抛出此codepen用于实验http://codepen.io/ihinckle/pen/JWGpQj?editors=1010

<div ng-app="directiveShare"> 
    <directive-a an-array="[1,2,3,4,5]"></directive-a> 
    <directive-b></directive-b> 
</div> 

angular.module('directiveShare', []) 
.directive('directiveA', function(){ 
    return { 
     restrict: 'E', 
     scope: { 
      anArray: '<' 
     }, 
     controller: function($scope, aService){ 
      $scope.clicked = aService.setIcon; 
     }, 
     template: ` 
      <ul> 
       <li ng-repeat="item in anArray" ng-click="clicked(item)">item</li> 
      </ul>` 
    } 
}) 
.directive('directiveB', function(){ 
    return { 
     controller: function($scope, aService){ 
      $scope.displayIcon = aService.getIcon; 
     }, 
     template: ` 
      <h1>{{displayIcon()}}</h1> 
      ` 
    } 
}) 
.factory('aService', function(){ 
    var srvc = {}; 

    srvc.setIcon = function(x){ 
     srvc.icon = x; 
    }; 

    srvc.getIcon = function(){ 
     if(srvc.icon){ 
      return srvc.icon; 
     }else { 
      return ''; 
     } 
    }; 

    return srvc; 
}); 

我用的指令在服务getter和setter和控制器暴露的功能。

相关问题