Saturday, 1 March 2014

Programatically changing an AngularJS scope variable and adding Firebug Lite to an AngularJs app

In this post I'm going to show two really nice tricks that help when developing AngularJS applications:
  • adding Firebug Lite to the current browser
  • changing the scope value outside a normal AngularJS controller, service or module
Let's say that we are inside Eclipse and have this simple AngularJS app (gist here)


... which looks like this when executed:


To add Firebug Lite to this page, all we need to do is to add a script reference to https://getfirebug.com/firebug-lite-debug.js


... and after refresh we will have a nice Firebug Lite console (and other nice goodies) at the bottom of our page :)


Next lets see how to access and change the AngularJS $scope of the ContactController.

The objective is to access programatically the New Contact value (set below to Hello Firebug :) )


In Firebug Lite, we can access the scope object by executing: var scope = angular.element(document.body).scope()


... and the New Contact value value using: scope.newcontact


If we change the New Contact value here (in Firebug Lite) using scope.newcontact = "Hello AngularJS"


... we will notice that the value will not automagically (ala AngularJS way) change in the binded (via ng-model) input field


The reason that didn't happen is because the change was done outside the AngularJS $digest cycle.

The solution is to call the scope.$apply() function (and the input field will be updated):


Post a Comment