简体   繁体   中英

Sending Angular Parameters to external JS file

Sending Parameters from AngularJS To JS File

I have been trying to send information from Angular to an external JS File for days now. I have tired the ng-model, ng-init, ng-bind and two way directives

<body lang="en" ng-app="app" ng-model="baseUrl='http://example.com'" >
<body lang="en" ng-app="app" ng-init=="baseUrl='http://example.com'" >

---- javascript

var app = angular.module('app', ['ui.grid','ui.grid.pagination']);
var baseUrl;

etc..etc..

Everything I have been seeing from the Angular Directive is to GET data from a java script variable. I need to SET a variable from Angular to a JS File.

The only way I found is to use :

    <script>
    var global = {
        baseUrl: 'http://example.com'
    };    
    </script>

before i declare

<body lang="en" ng-app="app" ng-model="baseUrl='http://example.com'" >

in the HTML

This is not an option for me. is there another way around it ? Any feedback is appreciated :)

You should not use directives to modify global data - that is the job of a service, or sometimes a controller. But, if you want to ignore this advice, you will need to put your logic in a lifecycle method of the directive. For example, you could add it to the link function. It's a horrible hack, but I already mentioned that.

var myModule = angular.module(...);

myModule.directive('directiveName', function factory(injectables) {
  var directiveDefinitionObject = {
    link: function postLink(scope, iElement, iAttrs) { 
       window.myGlobalVariable = 'Living dangerously';
    }
  };
  return directiveDefinitionObject;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM