当我尝试使用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>