Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind javascript method in Angularjs template

Tags:

angularjs

My application is using Angularjs at client side. I have five directive which are using same logic. Following are required details of my code

  1. I have one pure javascript class as AppUtilities.js having following method defined

    var AppUtilities = {
      //Get the guid for given collection
      getGUID: function (collectionName) {
          var prefix;
          var guid;
          //get first two character
          if (!Utilities.isEmpty(collectionName)) {
             prefix = collectionName.substring(0, 2);
             //Get timestamp
             var timestamp = Utilities.getTimestampId();
             //concate prefix to get the guid
             guid = prefix + timestamp;
          }
          return guid;
      }
    };
    
  2. I have five different directive in which I need to use "getGUID()" method to bind with template. Since template is only able to bind with scope function therefore I have defined scope method in all these five template as below

    scope.getGUID = function (collectionName) {
      return AppUtilities.getGUID(collectionName);
    }
    
  3. Then in all the five directive template, this method is bind as scope variable

    <h4 class="guid" id="guid" data-ng-bind-template="{{getGUID('goal')}}"></h4>
    

How can I avoid declaring these method as scope variable and directly use as AppUtilities.getGUID(collectionName) in the HTML template?

like image 387
joy Avatar asked Sep 27 '22 20:09

joy


1 Answers

There are multiple ways, but honestly, it seems like more effort than its worth, since you can just do:

scope.getGUID = AppUtilities.getGUID;

Of course, you could use $rootScope, but to me personally it feels wrong - I like when things are explicitly declared and do not magically appear.

Alternatively, if you only need to render the GUID in the UI, create a GUID directive. For example:

.directive("guid", function(){
  return {
    template: "<span>{{getGUID()}}</span>",
    link: function(scope, element, attrs){
       scope.getGUID = function(){
         return AppUtilities.getGUID(attrs.guid || attrs.name);
       };
    }
  }
});

and use as:

<h4 class="guid"><guid name="goal"></guid></h4>
like image 148
New Dev Avatar answered Oct 03 '22 02:10

New Dev