javascriptjqueryangularjscookiescookiestore

Basic Angular Input Control


I have a basic input control which has three bound events to it. The control displays a year value. On each event, the control should store it's value in a cookie so that on page refresh, the current value stays the same.

Events:

  1. onchange of the input itself (obviously)
  2. An arrow to the left of the input increments it
  3. An arrow to the right decrements it

I know how to do all of this in JQuery, but I'm trying to set this controller up in Angular. The control works great when you increment/decrement, but when the user manually edits the input, neither increment/decrement function work. I'm also suspicious that this is a very poor way to build this type of control... Below is my attempted code:

JS:

myApp.controller('TimeframeCtrl', ['$scope',
                                   '$cookieStore',
                                   function ($scope, $cookieStore) {
  // If year cookie doesn't exist
  if($cookieStore.get('year') == null) { 
    // Create year cookie
    $cookieStore.put('year', 2014); 
  }
  // Decrement year
  $scope.prevYear = function() {
    $scope.year = $scope.year - 1;
    $cookieStore.put('year', $cookieStore.get('year') - 1); 
  }
  // Increment year
  $scope.nextYear = function() {
    $scope.year = parseInt($scope.year) + 1;
    $cookieStore.put('year', $cookieStore.get('year') + 1); 
  }
  // User manually changes year
  $scope.yearChange = function() {
    // Not implemented
  }
  // Set timeframe control value
  $scope.year = $cookieStore.get('year');
}]);

HTML:

<form class="navbar-form pull-left" ng-controller="TimeframeCtrl">
  <i class="fa fa-angle-left" ng-click="prevYear()"></i>
  <input class="form-control" type="text" value="{{year}}" placeholder="Year" ng-blur="yearChange()"/>
  <i class="fa fa-angle-right" ng-click="nextYear()"></i>
</form>

Solution

  • Use ng-model to bind to $scope.year

    <input class="form-control" type="text" ng-model="year" placeholder="Year" />
    

    then use $watch to detect changes

     $scope.$watch('year', function() {
          // year has been manually changed, put your save logic here
       });
    

    But really you should create a directive, rather than a controller, than you will be able to reuse your component