gpt4 book ai didi

javascript - 从 JavaScript 调用 Angularjs $scope, "Uncaught TypeError: Cannot read property",angular.element

转载 作者:行者123 更新时间:2023-11-28 05:20:46 25 4
gpt4 key购买 nike

当我尝试使用 AngularJs 和 JavaScript 时,我尝试从外部 JavaScript 函数调用 $scope,但出现以下错误:

"Uncaught TypeError: Cannot read property 'message' of undefined" .

这是我的代码:

    <!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('app', []);
var msg = "new message"
app.controller('ctrl', ['$scope', function ($scope) {
$scope.message = msg;
}]);
function xfunc(){
var data = angular.
element(document.querySelector('[ng-controller="ctrl"]')).
scope().message;
return data
}
if (typeof 'xfunc()' !== 'undefined') {
console.log(xfunc());
}else{
console.log("the type of is : ", + typeof 'xfunc()')
}
</script>
</head>
<body>
<div ng-app="app" ng-controller="ctrl">
{{message}}
</div>
</body>
</html>

我确实从控制台调用了xfunc(),它工作正常,没有错误。
请问,有谁知道错误原因吗?是否可以仅使用纯 Javascript 和 AngularJS 来完成此操作,而无需第三方库? (当然如果可能的话)
提前致谢!

最佳答案

问题是在 AngularJs 启动之前调用的函数,所以解决方案是我添加了:

    document.addEventListener("DOMContentLoaded", function(event) {

});

在加载“body”之后加载“xfunc()”,所以这是我的最终代码:

    <!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('app', []);
var msg = "new message"
app.controller('ctrl', ['$scope', function ($scope) {
$scope.message = msg;
}]);
function xfunc(){
var data = angular.
element(document.querySelector('[ng-controller="ctrl"]')).
scope().message;
return data
}
document.addEventListener("DOMContentLoaded", function(event) {
if (typeof 'xfunc()' !== 'undefined') {
console.log(xfunc());
}else{
console.log("the type of is : ", + typeof 'xfunc()')
}
});
</script>
</head>
<body>
<div ng-app="app" ng-controller="ctrl">
{{message}}
</div>
</body>
</html>

关于javascript - 从 JavaScript 调用 Angularjs $scope, "Uncaught TypeError: Cannot read property",angular.element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40578151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com