AngularJS变量可从整个代码中访问


正如您所看到的,我打开了.xml文件并将其解析为xmlDoc。我试图实现的是,这个xmlDoc将可以从整个脚本中访问(我想稍后制作一些函数,这些函数将在屏幕上显示.xml中的元素(。我在网上搜索了一下,发现它可以通过全局变量$rootScope实现,但无法正确实现。我希望你们能帮助我。谢谢。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<p id="title">asd</p>
<button name="opt1" ng-click="">YES</button>
<button name="opt2" ng-click="">NO</button>
<script>
var app = angular.module('myApp', []);
var parser, xmlDoc;
app.run(function($rootScope, $http) {
text = $http.get("file.xml").then(function(response) {
return response.data;
}).then(function(text) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("title").innerHTML = 
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
});
});
</script>
</body>
</html>

在angular中有很多方法可以声明和使用全局变量。示例:1.使用$rootScope。我们需要在控制器或服务中添加一个依赖项,如:

app.controller('myCtrl', ['$rootScope', '$scope', function($rootScope, $scope){
$rootScope.yourVar = 'YourValue';
....
....
}]);
and then You can use this `yourVar` variable anywhere in your code.

另一种方法是使用CCD_ 1。

app.factory('factoryObj', ['$scope', function($scope){
let factoryObj.yourVar = 'yourValue';
return factoryObj;
}]);

现在,在任何控制器或任何其他服务中,通过使用这个factoryObj作为依赖项,然后在该控制器或服务中,我们可以使用factoryObj.yourVar作为变量。作为:

app.controller('myCtrl',['$rootScope','$scope','factoryObj'function($rootScope,$scope, factoryObj){
console.log('factoryObj.yourVar value: ',factoryObj.yourVar);
}]);

最新更新