Note that there are some explanatory texts on larger screens.

plurals
  1. POIs binding objects to angular's $rootScope in a service bad?
    primarykey
    data
    text
    <p>In angular, I have an object that will be exposed across my application via a service.</p> <p>Some of the fields on that object are dynamic, and will be updated as normal by bindings in the controllers that use the service. But some of the fields are computed properties, that depend on the other fields, and need to be dynamically updated.</p> <p>Here's a simple example (which is working on jsbin <a href="http://jsbin.com/erudis/21/edit" rel="nofollow">here</a>). My service model exposes fields <code>a</code>, <code>b</code> and <code>c</code> where <code>c</code> is calculated from <code>a + B</code> in <code>calcC()</code>. Note, in my real application the calculations are a lot more complex, but the essence is here.</p> <p>The only way I can think to get this to work, is to bind my service model to the <code>$rootScope</code>, and then use <code>$rootScope.$watch</code> to watch for any of the controllers changing <code>a</code> or <code>b</code> and when they do, recalculating <code>c</code>. But that seems ugly. <strong>Is there a better way of doing this?</strong></p> <hr> <p>A second concern is performance. In my full application <code>a</code> and <code>b</code> are big lists of objects, which get aggregated down to <code>c</code>. This means that the <code>$rootScope.$watch</code> functions will be doing a lot of deep array checking, which sounds like it will hurt performance.</p> <p>I have this all working with an evented approach in BackBone, which cuts down the recalculation as much as possible, but angular doesn't seem to play well with an evented approach. <strong>Any thoughts on that would be great too.</strong></p> <hr> <p>Here's the example application.</p> <pre><code>var myModule = angular.module('myModule', []); //A service providing a model available to multiple controllers myModule.factory('aModel', function($rootScope) { var myModel = { a: 10, b: 10, c: null }; //compute c from a and b calcC = function() { myModel.c = parseInt(myModel.a, 10) * parseInt(myModel.b, 10); }; $rootScope.myModel = myModel; $rootScope.$watch('myModel.a', calcC); $rootScope.$watch('myModel.b', calcC); return myModel; }); myModule.controller('oneCtrl', function($scope, aModel) { $scope.aModel = aModel; }); myModule.controller('twoCtrl', function($scope, aModel) { $scope.anotherModel = aModel; }); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload