如何将参数传递给angular中的指令函数?

时间:2017-05-26 14:40:33

标签: javascript angularjs angularjs-directive

我的HTML

<ul id="suggestions" class="suggestions-list"><li 
        ng-repeat="suggestion in suggestions track by $index" 
        class="suggestion-item" 
        ng-click="toggleSkill(suggestion, 'here')" 
        ng-class="{active : selectedIndex === $index}"
    ><span class="small clr-secondary">{{suggestion}} - {{$index}}</span></li></ul>

在指令中,我有:

link: function(scope, elem, attrs) {
  scope.toggleSkill = function(item, index) {
    debugger
    SkillsService.searchResults = []

    if (scope.selectedTags.indexOf(scope.suggestions[index]) === -1) {
      scope.selectedTags.push(scope.suggestions[index])
      scope.searchText = ""

由于某种原因,函数中的indexundefined形式出现。为什么会这样?

2 个答案:

答案 0 :(得分:1)

当我将其粘贴到模板/指令中时,你的代码工作正常。这是一个稍微简化的版本,便于阅读。检查一下是否有效。

<!--inside ur template-->
<p class="text" ng-click="zoo('param1', 'param2')">click me</p>

// inside ur directive
$scope.zoo = function (x, y) {
     console.log('my params ', x, y);
}

答案 1 :(得分:-1)

尝试:

ng-click="toggleSkill(suggestion, $index)"