2016-02-18 38 views
3

我正在使用angularjs使用元素指令來處理樣本播放器。我希望指令模板中的事件保持在指令中。換句話說,我如何在指令中使用控制器來創建僅限於指令模板內的元素的事件。爲什麼`replace:true`在AngularJS指令中不推薦

的指令:

logsApp.directive('logPlayer', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: {audio: '='}, 
     template: '<div ng-repeat="sample in audio">' + 
      '{{sample.title}}' + 
      '<button type="button" class="btn btn-default" ng-click="play()">Play</button>' + 
      '<button type="button" class="btn btn-danger" ng-click="stop()">Stop</button>' + 
      '</div>' 
    }; 
}); 

的唯一途徑,我可以得到NG-click事件到工作場所的事件方法在父控制器的$scope

logsApp.controller('LogListController', ['$scope', '$rootScope', 'LogsService', 'SoundManager', function($scope, $rootScope, LogsService, SoundManager) { 
    ... 
    $scope.play = function() { 
    SoundManager.sound.createSound({ 
     id: SoundManager.idPrefix + this.sample.id, 
     url: this.sample.filename, 
     autoLoad: true, 
     autoPlay: false, 
     onload: function() { 
      this.setPosition(0); 
      this.play({ 
       whileplaying: function() { 
        ... 
       } 
      }); 
     } 
    }); 
}; 

$scope.stop = function() { 
    SoundManager.sound.stopAll(); 
}; 

我將如何做到讓要包含在指令控制器中的play()stop()事件?

+1

將控制器添加到您的指令中。有關更多信息,請參閱[AngularJS綜合指令API](https://docs.angularjs.org/api/ng/service/$compile#comprehensive-directive-api)。 – georgeawg

+0

當我爲指令創建一個控制器,並應用'$ scope.play = function(){};'什麼也沒發生。 http://paste.ofcode.org/MBuDatxyYf2tDXp8BhgLcq – cj5

回答

2

當我爲指令創建一個控制器,並且應用$scope.play = function() {};什麼也沒有發生。

您遇到的問題是您正在使用replace: true已棄用。刪除它,你的指令的控制器將看到點擊事件。

angular.module("myApp").directive('logPlayer', function() { 
    return { 
     restrict: 'E', 
     //replace: true, 
     scope: {audio: '='}, 
     controller: function($scope) { 
      $scope.play = function(index) { 
       console.log("play clicked "+index); 
      }; 
     }, 
     template: '<div ng-repeat="sample in audio">' + 
     '{{sample.title}}' + 
     '<button type="button" ng-click="play($index)">Play</button>' + 
     '<button type="button" ng-click="stop($index)">Stop</button>' + 
     '</div>' 
    }; 
}); 

DEMO on JSFiddle

從文檔:

replace([!(已廢棄),將在下一主要版本中刪除 - 即V2.0)

指定哪些模板應更換。默認爲false

  • true - 模板將替換指令的元素。
  • false - 模板將替換指令元素的內容。

- AngularJS Comprehensive Directive API

從GitHub:

Caitp--它的反對,因爲那裏是已知的,很無聊的問題replace: true,其中不能真正被固定在一個數合理的時尚。如果你小心並避免這些問題,那麼給你更多的權力,但爲了新用戶的利益,只是告訴他們「這會讓你頭痛,不要這樣做」。

- AngularJS Issue #7636

在這種情況下隔離指令範圍鬥繼承了ng-repeat指令範圍。因此,請移除replace: true或從模板的頂部元素中移除ng-repeat

+0

謝謝!工作。那是因爲在事實之後替換更新DOM,並且事件變爲未綁定? – cj5

+1

'ng-repeat'覆蓋了指令的範圍。通常,** isolate **中的'ng-click'應該不能通過繼承連接到父函數。 **分離**範圍被「ng-repeat」銷燬。 – georgeawg

相關問題