0

I'm writing an on-page JS app with angular which will be integrated into different pages on our main website.

The app is integrated on our page with the following code:

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

data-level is used to filter the list. So far everything works fine.

Now I want to be able to change the level on the website (not inside the angular app!) without reloading the page.

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

This changes the DOM-Element as expected, but it's not recognized by angular. I tried attrs.$observe in the directive, but that didn't helped:

# 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

As we don't know by now who may implement our app as-well, I'm looking for a nice line of javascript like the one above!

Is there any way, that angular recognize a change of data-level, without calling a function like $apply() or $digest() with jQuery?

Frederik Kammer
  • 3,117
  • 3
  • 28
  • 29

1 Answers1

0

$digest cycle is the main thing which detects changes in scope variable and then updates the view any change in scope variable triggers it! you can read its details to understand why your view is not getting updated in your case i would suggest something like:-

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

in directives

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
}
Rishul Matta
  • 3,383
  • 5
  • 23
  • 29
  • This still won't update the dataLevel variable when the attribute is modified – JoseM Mar 14 '14 at 14:26
  • thats what i have written in the comment you can access parent level variables too by using scope.$parent.videoLevel so as i dont have your complete code check what works for you. – Rishul Matta Mar 14 '14 at 14:31
  • Thanks for your answer. Am I right, that I'll not be able to pass a custom `data-level` on initialization 'cause the 5 is hardcoded in the directive? That won't fit me needs – Frederik Kammer Mar 14 '14 at 14:42