richardjc
richardjc

Reputation: 89

Performance of .constant added to scope

I would like some thoughts on the performance of using constants in a view; is there a better way? (Bear with me, new to Angular)

I am injecting constants, 'fieldConst,' as a dependency into a controller, like so:

(function() {
'use strict';

angular
    .module('myApp')
    .controller('jobsCtrl', ['$scope', 'jobsService', 'fieldConst', jobsCtrl]);

    function jobsCtrl($scope, jobsService, fieldConst) {

        $scope.fieldConst = fieldConst;

        // get Jobs
        var state = jobsService.getState();
        $scope.jobs = state.jobs;
    }
})();

I am using these in my view, like so:

... 
<a ng-href="#" ng-repeat="job in jobs.records">
    <h5>{{ job[fieldConst.JOBNUMBER] }} {{ job[fieldConst.JOBTITLE] }}</h5>
    <small ng-switch on="job['isActive']">
...

Is this substantially less performant than using, say:

<h5>{{ job.JobNumber] }} {{ job.jobTitle] }}</h5>

I have a large number of fields/properties being used across the app, and the names of these as defined in a database, are subject to change; thus the desire to use constants

Upvotes: 1

Views: 66

Answers (2)

Eduard Jacko
Eduard Jacko

Reputation: 2151

Keep your view simple, otherwise it can become black hole which is hard to debug. That's why I personally suggesting to use job.JobNumber in your scenario. But you are already have a jobService service which should return you whatever you need. Just extend this service by methods getNumber() and getTitle(). If you are worried about updating the view after data changed outside of angular, you can use functions from view.

controller:

$scope.getTitle = function(){ return jobsService.getTitle(); };
$scope.getNumber = function(){ return jobsService.getNumber(); };
$scope.jobs = jobService.getState().jobs;

view:

<h5>{{jobsCtrl.getTitle()}} {{jobsCtrl.getNumber()}}</h5>

Don't worry much about performance (you can't feel difference as a user). If you keep your structure simple and modular, its easier to debug, extend and fixing bugs.

Hope that's help.

Upvotes: 0

Leandro Zubrezki
Leandro Zubrezki

Reputation: 1150

The performance is the same. Adding a variable to the $scope doesn't create a watcher. What creates a watcher is each {{}}, ng-if, ng-show, etc. Each {{}} has a expression that needs to be evaluated when the digest cycle runs and what Angular will do is check is that expression changed or not to update the view. So in your case the question is if job.JobNumber is more performant than job[fieldConst.JOBNUMBER].

So my final answer is FORGET ABOUT IT. Is exactly the same.

Upvotes: 1

Related Questions