如何更改此角度函数以使用指令

时间:2013-12-24 21:01:56

标签: javascript jquery angularjs

我知道dom操纵不应该在控制器中,所以我很好奇处理这些jquery事件的正确“Angular”方式。

这是我的控制器功能之一

    $scope.record = function (){
        $scope.slideChanges.push($scope.display);
        $scope.syncTimer.push(0);
        $scope.flashObject.doRecord();
        $("#Pause").removeClass().addClass("btn btn-warning");
        $("#Resume").removeClass().addClass("btn btn-default disabled");
        $("#Stop").removeClass().addClass("btn btn-danger");
        $("#Restart").removeClass().addClass("btn btn-primary");
        $("#Record").removeClass().addClass("btn btn-danger disabled");

    };

所以我可以删除此函数之外的dom操作,但仍然可以达到相同的效果。

1 个答案:

答案 0 :(得分:1)

您可以创建整个mediaplayer指令,也可以使用我在评论中描述的方法内联使用它。但是我觉得抽象它让它感觉更干净。

This plnkr包含如何创建某种受状态约束的媒体播放器指令的工作示例。

视图中生成的代码很小:

<div pf-music-player="somePlayer" file="{{fileToPlay}}"></div>

该指令的模板如下:

<span class="btn-group">
  <button class="btn" ng-disabled="state == states.Waiting || state == states.Loading"
    ng-class="{
        'btn-success': state == states.Stopped || state == states.Paused,
        'btn-danger': state == states.Playing
    }" ng-click="play()">Play</button>
  <button class="btn" ng-disabled="state == states.Waiting || state == states.Loading"
    ng-class="{
        'btn-success': state == states.Playing || state == states.Recording,
        'btn-danger': state == states.Paused
    }" ng-click="pause()">Pause</button>
  <button class="btn" ng-disabled="state == states.Waiting || state == states.Loading"
    ng-class="{
      'btn-success': state == states.Stopped || state == states.Paused,
      'btn-danger': state == states.Recording
    }" ng-click="record()">Record</button>
  <button class="btn" ng-disabled="state == states.Waiting || state == states.Loading"
    ng-class="{
      'btn-success': state == states.Playing || state == states.Recording || state == states.Paused,
      'btn-danger': state == states.Stopped
    }" ng-click="stop()">Stop</button>
</span>
<p ng-show="state != states.Waiting &amp;&amp; state != states.Loading">Playing {{songName}}</p>

函数play(),pause(),record(),stop()和字段state,states和songName由指令的链接函数提供。

执行指令take a look at the plnkr