Dinesh Kumar Soni Dinesh Kumar Soni - 5 months ago 7
AngularJS Question

Is there a way so we could create a global fuction that could be accessed all views in app in angularjs

I am developing phonegap app with ionic framework,in this app i have 13 controller and 13 views files in all views i need to call same function formateDateWithExtraValue(user.date), to call this function i have to declare this function in all 13 controllers like bellow

$scope.formateDateWithExtraValue = function(Udate){
"my code are here"
return result;
}

is there a way so we could write this function globally, so it could be accessible across all views.
like in PropertyView.html
{{ formateDateWithExtraValue(user.date) }}

Ken Ken
Answer

The most appropriate angular way to accomplishing this type of formatting in a view is to use a filter. The end result will permit use of your formatting function across all views.

I have provided a working example here: http://codepen.io/krcourville/pen/BzRxvr?editors=1010

Code

angular
  .module("app", [])

.controller("Controller1", function() {
  this.originalValue = "  I  have too     many spaces  !!";
})

.controller("Controller2", function($filter) {
      this.originalValue= "I    also   have too    many  spaces!!"

  var removespaces = $filter("removespaces");
  this.extra = removespaces("Something   extra   you   can  do");
})

.filter("removespaces", function() {
      return function(value) {
        if (typeof value === "string") {
          return value
            .split(" ")
            .filter(function(f) {
              return f !== "";
            })
            .join(" ");
        } else {
          return value;
        }
      };
});

View

<div ng-app="app">
  <p>
    Demonstrates using of filter across multiple controllers.
  </p>

  <div ng-controller="Controller1 as $ctrl">
    <h2>Controller1</h2>

    <p>
      Original Value:<pre>{{ $ctrl.originalValue }}</pre> 
    </p>

    <p>
      filtered: <pre>{{ $ctrl.modifiedInCtrl | removespaces }}</pre> 
    </p>

  </div>

<div ng-controller="Controller2 as $ctrl">
  <h2>Controller2</h2>

  <p>
      Original Value:<pre>{{ $ctrl.originalValue }}</pre> 
    </p>

    <p>
      filtered: <pre>{{ $ctrl.originalValue | removespaces }}</pre> 
    </p>

    <p>
      extra (using the filter in a controller): <pre>{{ $ctrl.extra }}</pre>
  </p>

</div>


</div>

More information here: https://docs.angularjs.org/guide/filter