2015-12-26 116 views
1

我想使用指令來顯示一組數據。因爲我製作了這樣一個元素:<jobs type="1" />;屬性類型決定了用戶應該看到的作業類型,並在我的模板中過濾我有以下代碼:<div ng-repeat="job in jobs | filter:{'type':type}">{{job.title}}</div>通過角度指令內部的服務進行過濾

問題我有我是不能弄清楚如何從我的元素採取屬性值,並推動它與我的服務結果一起,而沒有使角度生氣。

我的指令:

angular.module('myApp').directive('jobs', jobsDirective); 

jobsDirective.$inject = ['jobService','$scope','$sce']; 


    function jobsDirective(jobService, $scope, $sce) { 

     //this return results 
     var jobs = jobService.getAllJobs().success(function (data, status, headers, config) { 
      return data; 
     }); 


     return { 
      restrict:'E', 
      replace:true, 
      templateUrl:'templates/jobs.html', 
      scope: {  
       type:'@' 
      }, 
      link: function(scope){ 
       scope.jobs = jobs; 
      } 
     } 
    } 
+0

嘗試爲您的指令創建一個控制器函數,然後在控制器中注入範圍服務,您將可以訪問'type'屬性。基於這個值調用你的服務在控制器功能裏面 –

+0

我可以爲指令創建控制器嗎?無法找到一個參考它在谷歌 – Ash

+0

剛剛發現一個:-p – Ash

回答

2

這裏使用控制器獲取類型屬性的代碼。 注意,在指令定義中使用bindToController屬性,可以通過範圍服務和controllerAs別名訪問類型屬性,在這種情況下稱爲ctrl

angular 
    .module('myApp') 
    .directive('jobs', jobsDirective); 

    function jobsDirective() { 

     return { 
      restrict:'E', 
      replace:true, 
      controller: jobsCtrl, 
      controllerAs: 'ctrl', 
      bindToController: true, 
      templateUrl: 'templates/jobs.html', 
      scope: {  
       type:'@' 
      } 
     } 
    } 

    jobsCtrl.$inject = ['$scope', 'jobService']; 

    function jobsCtrl($scope, jobService, $sce) { 
     var vm = this, 
     type = $scope.ctrl.type; 
     //USE THE TYPE ATTRIBUTE TO GET THE JOBS ACCORDING THE TYPE 
     jobService.getAllJobs(type).success(function (data, status, headers, config) { 
      vm.jobs = data; 
     }); 

    } 
+0

謝謝你教我在我的指令和bindToController&controllerAs中使用控制器。我迄今爲止最棒的聖誕禮物哈哈 – Ash

0

這裏是工作的代碼;我剛剛爲該指令添加了一個控制器。

"use strict"; 
/* 
e.g. <jobs type="1" /> 
*/ 
angular.module('myApp').directive('jobs', jobsDirective); 
angular.module('myApp').controller("jobsCtrl" ,jobsCtrl); 

    jobsCtrl.$inject = ['$scope', 'jobService']; 

    function jobsCtrl($scope, jobService, $sce) { 

     jobService.getAllJobs().success(function (data, status, headers, config) { 
      $scope.jobs = data; 
     }); 

    } 

    function jobsDirective() { 

     return { 
      restrict:'E', 
      replace:true, 
      controller: 'jobsCtrl', 
      templateUrl:'templates/jobs.html', 
      scope: {  
       type:'@' 
      } 
     } 
    }