AngularJS对html标签更改的触发操作

时间:2014-03-14 13:46:18

标签: jquery angularjs angularjs-directive

我正在编写一个带有角度的页面JS应用程序,它将被集成到我们主网站的不同页面中。

该应用程序已在我们的页面上集成,其代码如下:

<div class="app-video-list" ng-app="videoList">
  <video-list id="video-list" data-level="5"></video-list>
</div>

data-level用于过滤列表。到目前为止一切正常。

现在我希望能够在不重新加载页面的情况下更改网站上的level(不在角度应用内!)。

$("#video-list").attr("data-level", "3");

这会按预期更改DOM-Element,但不会被angular识别。我在指令中尝试了attrs.$observe,但这没有帮助:

# CoffeeScript
angular.module('videoList').directive 'videoList', ($document, templateBase) ->
  restrict: 'E'
  replace: true
  templateUrl: templateBase + 'video_list.html'
  link: (scope, element, attrs) ->
    attrs.$observe 'level', (value) ->
      console.log 'level changed to ' + value

由于我们现在还不知道谁可以实现我们的应用程序,我正在寻找一个很好的javascript系列,如上所述!

有没有办法,角度识别data-level的变化,而不用jQuery调用$apply()$digest()这样的函数?

1 个答案:

答案 0 :(得分:0)

$ digest循环是检测范围变量更改然后更新视图的主要内容,范围变量的任何更改都会触发它!您可以阅读其详细信息,以了解为什么您的视图未在您的案例中得到更新我会建议如下: -

<div class="app-video-list" ng-app="videoList">
 <video-list id="video-list" data-level="{{videoLevel}}"></video-list>
</div>
指令中的

angular.module('videoList').directive 'videoList', ($document, templateBase) ->
restrict: 'E'
replace: true
templateUrl: templateBase + 'video_list.html'
link:function (scope, element, attrs) {
   if(!attrs.dataLevel){
scope.videoLevel="5"; //if your directive has isolated scope which doesnt seem to be the case here then use scope.$parent.videoLevel=5;
}


//your logic follows! and whenever you change the value of binded variable the changes will be reflected
}