![](/img/trans.png)
[英]How to change a $scope variable outside the controller in angularjs
[英]Access variable outside controller in angularjs
我想訪問或寧願使用在控制器之外作為常規變量在控制器中修改和初始化的變量。
這是控制器:
my.app.controller('queryCtrl', ['$scope','$http',function($scope,$http){
var tempAstData={
'rightNode': 'longitude = 72.8604836',
'leftNode': {
'rightNode': 'latitude = 19.1738427',
'leftNode': "fence_brand_name = 'taco'",
'centerOperator': 'AND'
},
'centerOperator': 'AND'
}
// some functions on it
}]);
//normal javascript
// want to use tempAstData here as plain java script in this same file....
//this part is not a controller or anyway related t angular js . This is plane java script.
我是新來的有角的,任何幫助都是值得的。
var myGlobalVariable = null;
my.app.controller('queryCtrl', ['$scope','$http',function($scope,$http){
var tempAstData={
'rightNode': 'longitude = 72.8604836',
'leftNode': {
'rightNode': 'latitude = 19.1738427',
'leftNode': "fence_brand_name = 'taco'",
'centerOperator': 'AND'
},
'centerOperator': 'AND'
}
myGlobalVariable = tempAstData;
// some functions on it
}]);
alert(myGlobalVariable);
//normal javascript
// want to use tempAstData here as plain java script in this same file....
//this part is not a controller or anyway related t angular js . This is plane java script.
使用$rootScope
以角度方式全局引用數據
my.app.controller('queryCtrl', ['$scope','$http','$rootScope',function($scope,$http,$rootScope){
var tempAstData={
'rightNode': 'longitude = 72.8604836',
'leftNode': {
'rightNode': 'latitude = 19.1738427',
'leftNode': "fence_brand_name = 'taco'",
'centerOperator': 'AND'
},
'centerOperator': 'AND'
}
$rootScope.tempAstData = tempAstData;
// some functions on it
}]);
那么您可以將$rootScope.tempAstData
用於其他控制器
my.app.controller('otherCtrl', ['$scope','$http','$rootScope',function($scope,$http,$rootScope){
console.log($rootScope.tempAstData)
})
正如@Subhash在此問題的評論中提到的,他在您的控制器中有3個異步方法。 然后,他需要在以下異步方法之后操作您的tempAstData變量:
@trichetriche我的控制器中有3個asyn方法,它們通過POST請求命中服務器。 我沒有在這里發布它以避免並發症。確切地說,我想使用腳本標簽new Treant(tempAstData)訪問html文件中的tempAstData。
在這種情況下,我建議使用$ q等待所有promise,並在此調用之后操縱tempAstData的方法,如下所示:
my.app.controller('queryCtrl', ['$scope','$http', '$q',function($scope, $http, $q) {
var wrapMethod = function (parameter) {
// do something with parameter
}
var tempAstData={
'rightNode': 'longitude = 72.8604836',
'leftNode': {
'rightNode': 'latitude = 19.1738427',
'leftNode': "fence_brand_name = 'taco'",
'centerOperator': 'AND'
},
'centerOperator': 'AND'
}
var promises = [];
// add promises returned by assync methods to a array
promises.push(assyncMethod1());
promises.push(assyncMethod2());
promises.push(assyncMethod3());
// wait all promises to be resolved
$q.all(promises).then(function () {
// call wrap method with 'normal' JavaScript code previously in a script tag
wrapMethod(tempAstData);
})
}]);
@Subhash請編輯您的問題,並添加完整的信息以供其他用戶使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.