如何在角度控制器中使用按钮ID?

时间:2015-07-10 02:52:06

标签: javascript angularjs

基本上,我有一个包含.mp3的字符串数组,我想使用自定义指令[ngAudio] [1]来播放。我认为这样做的一个好方法是为每个按钮分配一个id,将id传递给一个函数,然后检查包含将要播放的mp3的字符串的传递数组索引。

然而,我无法让它发挥作用。这是我的HTML:

<button id=0 type="button" class="btn btn-primary" ng-click="setSound(id) ; sound.play()">Sound 1</button>

(sound.play()来自ngSound,它只是一个播放加载声音的功能) 我也尝试过:     声音1 (其中id =&#34; 0&#34;而不是id = 0)

我的棱角分明:

myApp.controller('mainCtrl', ['$scope', 'ngAudio', function($scope, ngAudio) {
    var allSoundBites = [
        'resources/audio/test.mp3'
    ];

    $scope.setSound = function(id) {
        alert(id);
        $scope.sound = ngAudio.load(allSoundBites[id]);
    };
}])

如果不是做

,它可以正常工作
ng-click="setSound(id)"

我做

ng-click="setSound(0)"

但理论上不应该是通过的方式吗?

编辑:再次看到这个问题后,我意识到这实际上是毫无意义的,因为它实际上只需要更少的代码就可以将数字传递给函数,而不是使用ID ......

......仍然很好奇为什么这不起作用。

[1]:

3 个答案:

答案 0 :(得分:4)

问题

当您id作为参数时,它正在寻找$scope.id,但它不存在。

一个选项是使用$event读取元素的ID,但如果您在其他地方使用$scope方法,则可能很烦人,无论如何,它和#39;没有人需要的耦合水平。

建议的解决方案

我将在此处做出一个假设,即id由评论中推测的ng-repeat设置。如果是这样的话,你可以这样做:

<强>控制器

myApp.controller('mainCtrl', ['$scope', 'ngAudio', function($scope, ngAudio) {
    $scope.allSoundBites = [
        {name: 'Sound 1', path: 'resources/audio/test.mp3' }
    ];

    $scope.setSound = function(path) {
        $scope.sound = ngAudio.load(path);
    };
}]);

<强>模板

<button ng-repeat="soundBite in allSoundBites" id="sb-{{$index}}"
  class="btn btn-primary" ng-click="setSound(soundBite.path); sound.play();">
    {{soundBite.name}}
</button>

答案 1 :(得分:1)

选项1 按钮1

如果您没有ng-repeat,即只有一个按钮,则可以使用ng-init

选项2 按钮2&amp; 3

如果您使用ng-repeat即多个按钮,则可以使用类似于@ scarl3tt解决方案的$ index。

以下是JS FIDDLE

<div ng-app="clicker" ng-controller="mainCtrl" ng-init="id=0">
    {{test}}

    <button id=id  type="button" class="btn btn-primary" ng-click="setSound(id)">Sound 1</button>
    <br>
    <button ng-repeat="button in buttons" id={{$index}} type="button" ng-click="setSoundOther($index)" >{{button.btnName}}</button>

答案 2 :(得分:0)

如果我没有错,你有重复,在里面你有上面的按钮。

  • 您必须按索引(它的特殊范围属性)跟踪项目,将其传递给函数。

  • 其他方法是你可以在你的数组中的每个iterm中添加id属性,然后将item.id传递给你的函数。

如果您可以分享小提琴或下注演示,那就太棒了。

如果我误解了您的问题,请告诉我。