AngularJS custom ngBindModel directive

Bind ngModel to a variable whose name is stored inside another variable.

by gangadharjannu

HTML

<script src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<!doctype html>
<html lang="en" ng-app="myApp">
    
    <head>
        <meta charset="utf-8" />
        <title>My AngularJS App</title>
    </head>
    
    <body ng-controller="stageController">
        <form name="myForm" novalidate="">
           <input type="text" name="myText" ng-bind-model="model" />
        </form>
        <a ng-click='change();'>Change</a>
    </body>

</html>

CSS

input {
    width:240px;
    padding:2px 4px;
}

JavaScript

'use strict';

angular.module('myApp', ['myApp.directives']);

function stageController($scope) {
    $scope.model = 'realModel';    
    $scope.realModel = 'initial value of the field';

    $scope.$watch('realModel', function() {
        console.info("realModel changed to "+$scope.realModel);
    });
        
    $scope.change = function() {
        $scope.realModel = 'bruno';
    }       
}

angular.module('myApp.directives', [])
.directive('ngBindModel',function($compile){
    return{
        compile:function(tEl,tAtr){
            tEl[0].removeAttribute('ng-bind-model');
            return function(scope){
                tEl[0].setAttribute('ng-model', scope.$eval(tAtr.ngBindModel));
                $compile(tEl[0])(scope);
                //console.info('new compiled element:',tEl[0])
            }
        }
    }
});