Angular: Using ng-model in directive

Demo to show the usage of ng-model in a directive

by Pratik Bhattachary

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="timeCtrl">
  Timestamp(model) -
  <input tyep='text' ng-model='timestamp' />
  <br/>
  <time-dir ng-model='timestamp'></time-dir>
</div>

JavaScript

var myApp = angular.module('myApp', []);

myApp.controller("timeCtrl", function($scope) {
  $scope.timestamp = 0;
});

myApp.directive("timeDir", function() {
  return {
    restrict: "A/E",
    template: "Min - <input type='text' ng-model='time.min'></input><br/>Sec - <input type='text' ng-model='time.sec'></input>",
    require: "ngModel",
    link: function(scope, element, attr, ngModelCtrl) {
      ngModelCtrl.$formatters.push(function(modelValue) {
        var mins = parseInt(modelValue / 60);
        var secs = modelValue % 60;
        return {
          min: mins,
          sec: secs
        }
      });

      ngModelCtrl.$render = function() {
        scope.time = ngModelCtrl.$viewValue;
      }

      ngModelCtrl.$parsers.push(function(viewValue) {
        var totalSec = parseInt(parseInt(viewValue.min * 60) + parseInt(viewValue.sec));
        return totalSec;
      });

      scope.$watch('time', function() {
        ngModelCtrl.$setViewValue(scope.time);
      }, true);
    }
  }
});