Skip to content

Instantly share code, notes, and snippets.

@ecowden
Created January 16, 2013 20:33
Show Gist options
  • Save ecowden/4550671 to your computer and use it in GitHub Desktop.
Save ecowden/4550671 to your computer and use it in GitHub Desktop.
Use the Angular scope.$watch function to observe changes to a scope variable
/*
* Observe the "recentTimesheets" scope variable and calculate a derived value when
* it changes.
*
* The last parameter (true, in this case) instructs the watch to use object equality.
* If we set this to false or omitted it, the watch expression would use reference
* equality instead. This can make a huge difference! For instance, if you are using
* an Angular $resource to set the watched variable, the $resource.xxx() methods
* return an empty object immediately, then populate it when the XHR returns.
*
* Do your tests not trigger the watch expression? That's because we need to invoke
* scope.$apply(). This usually gets triggered automatically, but not in tests.
*
* See http://docs.angularjs.org/api/ng.$rootScope.Scope
*/
$scope.$watch("recentTimesheets", function () {
$scope.creatableTimesheetDates = creatableTimesheetDates();
}, true);
/*
* Do your tests not trigger the $watch expression? That's because we need to invoke
* scope.$apply(). This usually gets triggered automatically, but not in tests.
*/
it("should update scope.creatableTimesheetDates when scope.recentTimesheets changes", function () {
scope.creatableTimesheetDates = "before";
scope.recentTimesheets = [];
expect(scope.creatableTimesheetDates).toBe("before"); // haven't called $apply yet
scope.$apply();
expect(scope.creatableTimesheetDates).not.toBe("before");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment