将 JavaScript 变量传递给 AngualrJs ng-init

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21390917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:48:44  来源:igfitidea点击:

Pass JavaScript variable into AngualrJs ng-init

javascriptangularjs

提问by Ravi Ram

I have the following javascript variable defined and need to pass the memIdvalue into AngularJs init function.

我定义了以下 javascript 变量,需要将memId值传递给AngularJs init 函数。

<script type="text/javascript">
    var memId = "bb7de28f-0f89-4f14-8575-d494203acec7";
</script>   

<div id="content-header" class="mini" ng-init="getMember(memId)">

I am getting an error : memIdis not defined.

我收到一个错误:未定义 memId

Console shows the memIdvalue inside ng-init is not getting passed in.

控制台显示ng-init中的memId值没有被传入。

How can I pass in the javascript variable into ng-init?

如何将 javascript 变量传入 ng-init?

回答by qwertynl

You need to do it in the "angular" way by using $window:

您需要使用$window以下方法以“角度”方式进行操作:

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.memId = $window.memId;
}]);

Demo: http://codepen.io/qwertynl/pen/jqIrK

演示:http: //codepen.io/qwertynl/pen/jqIrK

回答by Satpal

Currently Your variables are bounded to window object. You can use Angular $windowto access global window object

目前你的变量被绑定到 window 对象。您可以使用 Angular $window访问全局窗口对象

// Your Global Variable defined outside angular
var memId = "bb7de28f-0f89-4f14-8575-d494203acec7";

//Define Module
var app = angular.module('myapp', []);

//Define Controller
app.controller('MyCtrl', ['$scope', '$window',
    function($scope, $window) {
        $scope.memId = $window.memId;
    }
]);

回答by SPR

For angular 2, you can achieve this by using below:

对于角度 2,您可以使用以下方法实现:

In your jQuery app, declare a variable and assign it to window object: window.glb = "This is global". In your angular app, add the below line anywhere before your component declaration: declare var window: any; Then in your ngOnInit, you can access the global variable as below: window.parent.

在您的 jQuery 应用程序中,声明一个变量并将其分配给 window 对象:window.glb = "This is global"。在您的 Angular 应用程序中,在组件声明之前的任何位置添加以下行:declare var window: any; 然后在你的 ngOnInit 中,你可以访问全局变量,如下所示:window.parent。