未定义变量AngularJS
Undefined variable AngularJS
为什么我不能通过一个函数得到我的值?我正在为测试做休息请求,所以你只能得到一个日期,并且总是告诉我值未定义。
例子$http.get('app/components/home/controller/test_calendar.json').then(function(value) {
$scope.example2 = value.data.data[0];
//console.log($scope.example2);
});
$scope.setDayContent = function(date, content) {
console.log($scope.example2);
};
我得到一个值undefined
与$scope。Example2或其他值。对于我的第一个控制台,数据看起来很好
我认为你在http请求(这是异步的)完成之前调用setDayContent(),所以在$scope之前。设置Example2。你可以通过取消'then'函数中console.log的注释来检查这一点,看看你是否有你的值。
如果您的函数setDayContent()是从html中的用户操作调用的(我想,因为它在作用域中)-例如按钮-您可以禁用它,直到数据被加载,像这样:
<button ng-click="setDateContent(...)" ng-disabled="!example2">
- 因为你的$http.get()是异步调用
- 检查Web控制台(F12)和XHR呼叫响应,改变你的分配和调用setDayContent在你的回调函数。
您需要调用$scope。setDayContent函数从json中获取值后,注意$http调用是异步的
// Code goes here
angular
.module('myApp', [])
.run(function($rootScope) {
$rootScope.title = 'myTest Page';
})
.controller('testController', ['$scope', '$http',
function($scope, $http) {
/*my JSON file test_calendar.json
test_calendar = {
"data": [{
"name": "nikhil"
}]
}*/
$http.get('test_calendar.json').then(function(value) {
$scope.example2 = value.data.data[0];
$scope.setDayContent();
});
$scope.setDayContent = function(date, content) {
alert($scope.example2);
};
}
])
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body data-ng-controller="testController">
<p></p>
</body>
</html>
相关文章:
- Ionic:AngularJS变量未使用$scope更新DOM
- 浏览器's将AngularJS变量加载为URL
- 将AngularJS变量发送到新的弹出窗口
- AngularJS变量转换为html<对象>属性
- 如何在javascript数据字段中绑定AngularJs变量
- 错误:AngularJs 变量未定义,当使用 grunt 运行时.(泽泽尔)
- AngularJS变量未显示在html中
- 如何在 JavaScript 函数中包含 AngularJS 变量
- 在$http之前调用时不显示 Angularjs 变量
- 将 JavaScript 数组值分配给 AngularJS 变量
- 将 Json 文件存储在 AngularJS 变量中,以便与“ng-repeat”一起使用
- AngularJs变量未显示在视图中
- angularjs变量无法在函数调用外访问
- 如何在脚本中定义angularjs变量
- 如何从模板脚本访问AngularJS变量
- Angularjs变量undefined、null和empty同时出现
- 如何将AngularJS变量绑定为一个Polymer全局变量
- 当AngularJS变量在$scope中定义时使用对象名
- Angularjs -变量未找到
- 用JavaScript添加新的AngularJS变量