未定义变量AngularJS

Undefined variable AngularJS

本文关键字:AngularJS 变量 未定义      更新时间:2023-09-26

为什么我不能通过一个函数得到我的值?我正在为测试做休息请求,所以你只能得到一个日期,并且总是告诉我值未定义。

例子
$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()是异步调用
  1. 检查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>