简体   繁体   English

将Angular参数发送到外部JS文件

[英]Sending Angular Parameters to external JS file

Sending Parameters from AngularJS To JS File 从AngularJS发送参数到JS文件

I have been trying to send information from Angular to an external JS File for days now. 我几天来一直试图将信息从Angular发送到外部JS文件。 I have tired the ng-model, ng-init, ng-bind and two way directives 我已经厌倦了ng-model,ng-init,ng-bind和双向指令

<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 ---- javascript

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

etc..etc.. etc..etc ..

Everything I have been seeing from the Angular Directive is to GET data from a java script variable. 我从Angular Directive看到的一切都是从java脚本变量中获取数据。 I need to SET a variable from Angular to a JS File. 我需要将一个变量从Angular设置为一个JS文件。

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 在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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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