Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs setting default values to display before evaluation

Tags:

angularjs

I used angularJs for really simple functionality on an existing site.

it is something like this

<div ng-app>
    <div ng-controller="TermsController">
        <input type="checkbox" ng-model="terms.agree" />
        <input type="submit" value="{{terms.label}}" .. />
    </div>
</div>

I plug angular in the middle of the page and everything is working fine except the fact that angular loads quite slow and user can see {{terms.label}} for a moment before angular evaluates its value.

i tried to do something like

<input type="submit" value="Default value" ng-model="terms.label" .. />

but it never updated the value of the submit button. anyway I would bet I've seen something like this, but maybe input field was without value attribute and only model.

any guidance as to how to setup the template before angularJs loads are appreciated.

I know that I can set some preloader and replace it once angular has loaded, but for this simple task it seems to be an overkill.

thanks for help

like image 834
pawel.kaminski Avatar asked Nov 08 '12 15:11

pawel.kaminski


2 Answers

You can hide element with the ng-cloak attribute during loading:

<div ng-app>
    <div ng-controller="TermsController" ng-cloak>
        <input type="checkbox" ng-model="terms.agree" />
        <input type="submit" value="{{terms.label}}" .. />
    </div>
</div>

Reference: http://docs.angularjs.org/api/ng.directive:ngCloak

like image 192
JvdBerg Avatar answered Oct 17 '22 22:10

JvdBerg


The best what you can do with the existing version of AngularJS is to us the ng-bind directive. From its documentation:

Once scenario in which the use of ngBind is prefered over {{ expression }} binding is when it's desirable to put bindings into template that is momentarily displayed by the browser in its raw state before Angular compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

To make the ng-bind work in your case you would have to change the input tag to a button tag like so:

<div ng-controller="TermsController">
    <input type="checkbox" ng-model="terms.agree">
    <button type="submit" ng-bind="terms.label">Before</button>
</div>

Here is a working jsFiddle: http://jsfiddle.net/TL33r/2/

You could use ng-cloak (see another question for more info) but ng-cloak will hide the whole DOM element (and its children) while I believe that you've asked for having a "default" value that gets changed to a binding when AngularJS kicks in.

like image 22
pkozlowski.opensource Avatar answered Oct 17 '22 22:10

pkozlowski.opensource