2017-03-01 91 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和控制器暴露的功能。

相關問題