Angularjs Directive does not respond to attribute change

I have a chat directive that I use to place chat on a page.

mod.directive('chat', function () { return { templateUrl: '/chat', replace: true, scope: { chatID:'@chat', }, controller: function ($scope, $element, $timeout) { var id = $scope.chatID ... }, link: function ... } }) 

HTML looks like this:

 <div class="chat" chat="{{currentChatID}}" ui-view="currentChat"></div> <div class="content" ui-view="mainContent"></div> 

This is a file called "standard"

 mod.config(function($stateProvider) { $stateProvider.state('standard', { views: { 'main': { templateUrl: '/tmpl/standard', controller: function($scope, $timeout) { $scope.currentChatID = '' $scope.setCurrentChatID = function(newID) { $scope.currentChatID = newID } } } } }) }) 

I am using angularjs-ui-router to create a parent view with a chat directive that provides chat inside this view. This works great when loading the first page, the chat is loading. But when I change the page / chat room, I use a different controller to run setCurrentChatID() . This changes the currentChatID for the chat item in the DOM, I also see that the chat item properties are changing to the new ID in angularjs-batarang, but the chat controllers do not start. How can I make this work correctly / activate chat controllers when changing chatID.

Thanks.

+4
source share
1 answer

It's hard to say without seeing the rest of your chat controller code, but you might need $watch inside your chat controller, for example:

 $scope.$watch('chatID', function(newValue, oldValue) { // run some code here whenever chatID changes }); 

EDIT: For more information on the $digest and Angular runtime loops, see this AngularJS tutorial , (Check out the Runtime section)

For more information about controllers, see this guide , Angular JS: Understanding Controllers . Here are the key points related to your question:

Controllers should only be used for:

  • Set the initial state of the area object.
  • Add scope object behavior. (enable creation of $watch , etc.).

Only the $digest loop is executed:

  • $evalAsync
  • list of $watch
+4
source

Source: https://habr.com/ru/post/1481680/


All Articles