2017-09-16 39 views
0

我想在我的項目中創建一個下拉篩選器。所以,我使用指令創建了下拉列表,其中列表包含模板中的ng-click事件。我不知道我錯在哪裏。請提供解決方案。提前致謝。爲什麼ng-click不能在自定義指令模板上工作?

我的HTML文件

<div ng-controller="drop"> 
<a ng-click="toggleList">Select</a> 

<div ng-if="toggleDrop"> 
<drop-down></drop-down> 
</div> 
</div> 

我的控制器代碼

angular.module('myApp', []) 
    .controller('drop', ['$scope', function($scope){ 
    $scope.toggleDrop = false; 
    $scope.filterList = ['One','Two','Three']; 
    $scope.toggleList = function() { 
      $scope.toggleDrop = !$scope.toggleDrop; 
    } 

    $scope.filterContent = function() { 
      alert('dfdf') 
    } 

}]); 

我的指令代碼

angular.module('myApp', []) 
     .directive('dropDown', function() { 
    return { 
    restrict: 'E', 
    templateUrl: 'drop.html' 
    controller: drop 
    } 
}); 

我的指令模板文件

<ul> 
    <li ng-repeat="items in filterList" ng-click="filterContent()">{{items}}</li> 
</ul> 

一切工作正常,除ng-click行爲。提前致謝。

回答

2

有您的代碼很少出現問題,

(i)您的指令sh烏爾德沒有空的依賴一個新的模塊,將其更改爲,

angular.module('myApp') 
     .directive('dropDown', function() 

(ii)您缺少內部指令的控制器後一個逗號,

angular.module('myApp') 
     .directive('dropDown', function() { 
    return { 
    restrict: 'E', 
    templateUrl: 'drop.html', 
    controller: 'drop' 
    } 
}); 

(三)應toggleList()這是一個函數,

<a ng-click="toggleList()">Select</a> 

DEMO

+1

此外,在該指令分配控制器'控制器時,使用單引號:「drop'' –

+0

@SachilaRanawaka我不認爲這樣做'drop'控制器應內部指令中使用。因爲它已經在父控制器中使用過了..要麼我們應該爲'drop-down'指令代碼制定指令控制器代碼。或者我們可以在不指定控制器的情況下共享父控制器代碼 –

+0

@PankajParkar是的,但添加它也不會是一個問題 – Sajeetharan

1

你錯過括號調用函數的ng-click

ng-click="toggleList()" 

此外,在指令代碼不再次宣示角模塊。如果你認爲它會從該模塊中清除舊的註冊組件。使用angular.module('moduleName')(將返回創建模塊),而註冊新的組件模塊

angular.module('myApp', []) 

應該

//module getter 
angular.module('myApp') 

此外指令有錯DDO,糾正它下面

return { 
    restrict: 'E', 
    templateUrl: 'drop.html', //added `,` here 
    //I don't think so you need controller here as you shared the parent controller 
    //wrap with `'` but it will create `drop` controller instance inside directive again 
    //controller: 'drop' 
} 
0

您已給出函數名稱'toggleList',但您尚未調用函數。它應該在您調用該函數時工作如下:

<a ng-click="toggleList()">Select</a> 

您在函數中缺少括號。

感謝

相關問題