How to pass directive scope value to a global javascript function called in template of the same directive?

102 Views Asked by At

I've a question regarding the way values work in directives. I have one directive which has a template and in the same template I want to call a (globally defined) javascript function and into that javascript function I want to pass the value that I get from my directive (It might sound a bit confusing). Here is the example code.

angular.module("Shell").directive("myFormField", function () {
return {
    scope: {
        text: "@",
        required: "@",
    },
    transclude: true,
    replace: true,
    template:
        '<div>' +
        '<label style="white-space: nowrap;font-weight: normal;width: 100% !important">'+globalLoadText(text)+
        '<div style="margin-top: 1.5px;" ng-transclude />' +
        '</label>' +
        '</div>'
};
});

globalLoadText() is my global method defined out side angular(in a normal js file thats in the root scope) text would be the value that I want get from the directive.

I hope I have written down my question clearly. Any help would be highly appreciated. Thanks!!

1

There are 1 best solutions below

0
On

I strongly urge you to explain why you need a global function because its not hard to accomplish what you want. But that doesn't mean you should.

angular
  .module("Shell")
  .directive("myFormField", myFormFieldDirective);


myFormFieldController.$inject = ['$scope'];

function myFormFieldController($scope) {
  $scope.globalLoadText = _globalLoadText;

  function _globalLoadText() {
    return globalLoadText($scope.text);
  }
}


function myFormFieldDirective() {
  return {
    scope: {
      text: "@",
      required: "@",
    },
    transclude: true,
    replace: true,
    controller: myFormFieldController,
    template: '<div>' +
      '<label style="white-space: nowrap;font-weight: normal;width: 100% !important">{{globalLoadText()}}' +
      '<div style="margin-top: 1.5px;" ng-transclude />' +
      '</label>' +
      '</div>'
  };
}