Sunday, March 8, 2015

AngularJS tip, initialize and bind a variable using curly brackets

For tiny projects, sometimes we get too tired writing javascripts inside of script tags or even in external javascript files. I used the tip describe below in one of my blogspots where my laziness sometimes is triggered.

(Note: this tip is not advisable because it is better to initialize models at the controller).

In my tiny projects, I initialized variables or create new models inside of "ngHide". The created new models will at the same time listen and gets updated when the inputs are changed.

For example:
 buyprice:<input type="number" ng-model="BuyPrice" style="width:52px">,   
 sellprice:<input type="number" ng-model="SellPrice" style="width:52px">,   
 n:<input type="number" ng-model="Qty" min="1" style="width:100px">  
 <br/>  
 <br/>Net Income = <span style="font-size:18pt">P {{MyProfit.netincome|number:2}}</span>, Gain = <span style="font-size:18pt">{{MyProfit.gain|number:2}}%</span>  
 <br/>  
 <br/><span ng-hide="true">Profit: {{MyProfit = Profit(BuyPrice, SellPrice, Qty)}},</span>  

From the above "MyProfit" is initialized at the bottom. When BuyPrice, SellPrice, and Qty are updated, MyProfit gets updated also.

The only thing that was created inside of a javascript tag here was the Profit() function, and its long body is not shown in this article.

The Profit() function will return an object with "netincome" and "gain" as prorperties. The code below shows how MyProfit is used:
  <br/>Net Income = <span style="font-size:18pt">P {{MyProfit.netincome|number:2}}</span>, Gain = <span style="font-size:18pt">{{MyProfit.gain|number:2}}%</span>