0

I am learning Angular.js and i'm using ajax(jsonp) to return hotel data.

In the data is a set of Australian states however the data returned is NW,QL,VI,AC,TA. These need to be NSW,QLD,VIC,ACT,TAS so I need to write a function to add the extra character.

Can I achieve this via a custom filter using if or switch and render this straight in the view or do I need to create a factory and pass it through a function before it gets to the view?

Or use jquery?

ottz0
  • 2,595
  • 7
  • 25
  • 45
  • what is logic behind to add extra character ? – murli2308 Nov 24 '15 at 08:57
  • See [this answer](http://stackoverflow.com/a/15012542/3944708) on "“Thinking in AngularJS” if I have a jQuery background?" on using jquery. Where do you get these data from? – Ben Kauer Nov 24 '15 at 08:58
  • I am printing the states out onto the page. I am using the Hotel name, address, city and state and if you are Australian and see your state with 2 characters like american states it doesn't look too good – ottz0 Nov 24 '15 at 09:45

1 Answers1

0

1. approach:

I would suggest doing it when receiving the data.

function addThirdCharacter(arr) {
  // your logic of adding the character
}

$http({
  method: 'GET',
  url: '/states'
}).then(function successCallback(response) {
    $scope.states = addThirdCharacter(response)
  }, function errorCallback(response) {
    // Error handling
});

2nd approach

$formatters for ngModel: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

angular.module('myApp', ['ngSanitize']).
directive('addCharacter', ['$sce', function($sce) {
  return {
    restrict: 'A', // only activate on element attribute
    require: '?ngModel', // get a hold of NgModelController
    link: function(scope, element, attrs, ngModel) {
      if (!ngModel) {
         return; // do nothing if no ng-model
      }

      function formatter(value) {
        if (value) {
          return addThirdCharacter(value);
        }
      }
      ngModel.$formatters.push(formatter);
    }
  };
}]);

3rd approach

If that's not an option, I would add a custom directive for that, that show the correct value for each 2 character (look at viewValue and modelValue if you have ngModel available)

Documentation about directives: https://docs.angularjs.org/guide/directive

If you are new to directives I would suggest you this very very good tutorial post: http://www.ng-newsletter.com/posts/directives.html

Carl Ambroselli
  • 616
  • 6
  • 18