Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve Functional binding with ng-model (With plnkr)

I have a dob column and values comes in this is in yyyy-mm-dd format say 2013-01-01 and I need to show it in input box as 1 Jan. I can achieve this by writing a function and then return exact value from that function. But function could not be called from input box using ng-model where as it can be called using ng-bind in spans. I can understand that function calling in input box will break two way binding. But what other approach I can use for this.

http://plnkr.co/edit/pZDpypsxM1OA2JwFhjjp?p=preview

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" >
    var app = angular.module('app', []);
    app.controller('AppCtrl', function ($scope) {
        $scope.dob = "2013-01-01";
        $scope.getDateOfBirth = function(dob){
            var months = ["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"]
            var split = dob.split("-");
            return parseInt(split[2])+" "+months[parseInt(split[2])-1];
        }
    });
</script>

<span ng-app="app" ng-controller="AppCtrl" ng-bind="getDateOfBirth(dob)"></span>

<input type="text" ng-model="getDateOfBirth(dob)"/>
like image 937
Rohit Bansal Avatar asked Aug 22 '13 14:08

Rohit Bansal


1 Answers

You can use ng-init to assign the value returned by the function and assign it to a model:

<input ng-init="myDOB = getDateOfBirth(dob);" type="text" ng-model="myDOB">

DEMO

like image 107
zs2020 Avatar answered Nov 10 '22 07:11

zs2020