我正在使用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()
事件?
將控制器添加到您的指令中。有關更多信息,請參閱[AngularJS綜合指令API](https://docs.angularjs.org/api/ng/service/$compile#comprehensive-directive-api)。 – georgeawg
當我爲指令創建一個控制器,並應用'$ scope.play = function(){};'什麼也沒發生。 http://paste.ofcode.org/MBuDatxyYf2tDXp8BhgLcq – cj5