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)">

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.


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

  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

  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.
    angularjs training in Chennai | angularjs training institute in Chennai | FITA Academy reviews


What do you think?