最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angularjs - Pass JavaScript variable into AngualrJs ng-init - Stack Overflow

programmeradmin0浏览0评论

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

<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 : memId is not defined.

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

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

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

<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 : memId is not defined.

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

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

Share Improve this question edited Jan 27, 2014 at 21:13 Satpal 133k13 gold badges166 silver badges170 bronze badges asked Jan 27, 2014 at 20:24 Ravi RamRavi Ram 24.5k21 gold badges86 silver badges119 bronze badges 1
  • stackoverflow.com/a/19384128/1022697 <-- this might be your answer. – qwertynl Commented Jan 27, 2014 at 20:54
Add a comment  | 

3 Answers 3

Reset to default 12

You need to do it in the "angular" way by using $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

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

// 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;
    }
]);

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

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.

发布评论

评论列表(0)

  1. 暂无评论