Communication between controller and directive

41 views
Skip to first unread message

mark goldin

unread,
Sep 12, 2014, 10:23:16 AM9/12/14
to ang...@googlegroups.com
Trying to execute some code when controller needs to refresh an object in the view.
Both a controller and a directive in the same file.

var motoAdsApp = angular.module("motoAdsApp");
motoAdsApp.controller('AirportControllers', function($scope, $http, AirportService) {
    $scope.refresh

.....
});

motoAdsApp.directive('aDirective', 
function() {
    return {
      restrict: 'E',
      scope:    {
        refresh:   '='
      },
      link:     function(scope, element, attrs ) {
        scope.$watch('refresh', function() {
          alert(1234);
        })
      }
    };
}); .

At some point  in the controller I am changing refresh to true but no alert is fired. Please help.

Thanks

dinesh kumar

unread,
Sep 12, 2014, 10:38:49 AM9/12/14
to ang...@googlegroups.com
add this code in controller and check.

$timeout(function(){
   $scope.$apply();
})

Thanks
Dinesh kumar.L

mark goldin

unread,
Sep 12, 2014, 10:43:31 AM9/12/14
to ang...@googlegroups.com
Where do I add it?

--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/21u6sUGvPPk/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

dinesh kumar

unread,
Sep 13, 2014, 12:31:45 AM9/13/14
to ang...@googlegroups.com
In the airport controller

Thanks
Dinesh kumar l

Sander Elias

unread,
Sep 13, 2014, 2:46:04 AM9/13/14
to ang...@googlegroups.com
Hi Mark,


The refresh will take place in the next digest cycle. I suspect you expect the result right away. That's not how asynchronous code works.
(remember JavaScript is single threaded!). it might help if you read through the 'Integration with the browser event loop' part in the guide.

if you are changing the refresh value in a reaction on a outside event, you need indeed to call $apply, Calling $apply will kick in
an digest cycle. This is only needed if you makes changes to your data from functions that are called from outside angular.

Regards
Sander

dinesh kumar

unread,
Sep 13, 2014, 12:09:57 PM9/13/14
to ang...@googlegroups.com
hi mark,
i have created a jsbin link resembling your scenario.compare it with you code and check where you made the mistake.

as sander said it is true,i thought u r making a change in refresh by externals means,that is why i asked you update with the code.

check and tell me it worked or not,if not show the code where you change update the refresh variable.

Regards
Dinesh kumar.L

Reply all
Reply to author
Forward
0 new messages