3/1/15

AngularJS ng-model Concatenate Model Values

In order to concatenate a model property values in AngularJS, we need to create an extended property on the model and then use that property with the ng-model directive.

We can illustrate this with the following angular module:

        var app = angular.module('app', []);
        app.controller('AppCtrl', function ($scope) {
            $scope.customer = {name: 'ozkary', id: '1234' };


            $scope.allInfo = function (data) {
                return data.id + ' - ' + data.name;
            }
        });

On the view, we attempt the following:

<body ng-app="app" ng-controller="AppCtrl">

    <h2>Extended Property - ng-init expression</h2>   
    <h2>Bad - ng-model does not like expressions</h2>
    <input type="text" ng-model="allInfo(customer)">
</body>

The ng-model can only accept a property for a two way binding, so it does not work with an expression. Therefore, we need to create another property that meets our desired results. In order to do that, we can use the ng-init directive to evaluate an expression and assign the result to another property, info. We can then use ng-model directive with this new property. We can demonstrate this as follows:

    <input type="text" ng-model="customer.info"
               ng-init="customer.info = allInfo(customer)">

To view this in action visit this plunk:  http://plnkr.co/edit/PSvwCE?p=info
We can now take a complex model and create extended properties to easily bind it to the view.


Hope this tip is useful.

4 comments :

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Now only i understand the real difference between ng-init & ng-model. I thought ng-init supports one way binding. Please explain only one time binding in angular.js

    Angularjs Training | Angularjs Training in Chennai

    ReplyDelete
  3. AngularJs is an open source framework which is used to add details to the website. AngularJs is supported by google which a major advantage to the developers.
    Regards,
    angularjs training in Chennai | angularjs training institute in Chennai | FITA Academy reviews

    ReplyDelete
  4. Nice piece of information on HTML5. With the expansion of smartphones and other portable gadgets, the demand for responsive website design that go comfy on all devices keeps on increasing. This leads to invention and expansion of HTM5 web technology. PHP Training in Chennai

    ReplyDelete