Why variables defined in controller does not update within a directive?

4,895 views
Skip to first unread message

codef0rmer

unread,
Jan 1, 2013, 8:43:12 AM1/1/13
to ang...@googlegroups.com
I just noticed this issue while updating/mutating objects/variables defined in a controller by a directive in the same scope. Whats missing? 


var App = angular.module('objectMutation', []);

      App.controller('oneCtrl', function($scope, $timeout) {
        $scope.list1 = {'name': 'AngularJS'};
        $scope.list2 = [{name: 'AngularJS'}];
      
        $scope.emptyMe = function() {
          $scope.list1 = {};
          $scope.list2.length = 0;
        };
      });
        
      App.directive('fubar', function() {
          return {
            restrict: 'A',
            link: function(scope, element, attrs) {
              var update = function(newValue, oldValue) {
                $(element).unbind('click').click(function() {
                   scope.list1 = {};
                   scope.list2.length = 0;
                });
              };
              update();
            }
          };
        });

Pawel Kozlowski

unread,
Jan 1, 2013, 9:02:53 AM1/1/13
to ang...@googlegroups.com
Hi!

Classic one - you are missing scope.$apply while doing changes outside
of the AngularJS world (DOM event handler)
Here is the working jsFiddle: http://jsfiddle.net/Etb9d/

I can almost hear Witold mentioning something about the documentation :-)
But seriously, going over scope and directives documentation would
help you getting up to speed...

BTW: you really don't need jQuery for such simple manipulations.

Cheers,
Pawel
> --
> You received this message because you are subscribed to the Google Groups
> "AngularJS" group.
> To post to this group, send email to ang...@googlegroups.com.
> To unsubscribe from this group, send email to
> angular+u...@googlegroups.com.
> Visit this group at http://groups.google.com/group/angular?hl=en-US.
>
>



--
Question? Send a fiddle
(http://jsfiddle.net/pkozlowski_opensource/Q2NpJ/) or a plunk
(http://plnkr.co/)
Need help with jsFiddle? Check this:
http://pkozlowskios.wordpress.com/2012/08/12/using-jsfiddle-with-angularjs/

Looking for UI widget library for AngularJS? Here you go:
http://angular-ui.github.com/

codef0rmer

unread,
Jan 5, 2013, 3:49:52 AM1/5/13
to ang...@googlegroups.com
Oh Yeah. I'd already used $timeout instead of $apply... just forgot to add it in jsfiddle demo. I resolved the issue by using 
  scope.$parent.list1 = {} along with scope.list1 = {}.

Unfortunately I could not reproduce it for jsfiddle demo.
Reply all
Reply to author
Forward
0 new messages