ReferenceError:未定义myData

时间:2016-02-24 06:09:11

标签: angularjs json

我是learnig angular js service。尝试执行以下代码,该代码从json文件中读取JSON。

data.json

 {
   "name": "ishmam",
   "age": "23"
 }

HTML正文:

<body ng-app="myAppp" ng-controller="customersCtrl">


<div>
     {{myData.name}}
</div>

    <script>
         var app = angular.module('myAppp', []);
         app.controller('customersCtrl', function($scope, $http) {
             $http.get('data.json').then(function (response) {
                 $scope.myData = response.data.records;
                 console.log("sadas"); //this is ok
                 console.log(myData.name); //this is showing error
             });
         });
    </script>

 </body>

收到以下错误:

ReferenceError: myData is not defined
  at MyAJ.html:30
  at processQueue (angular.js:15552)
  at angular.js:15568
  at Scope.$eval (angular.js:16820)
  at Scope.$digest (angular.js:16636)
  at Scope.$apply (angular.js:16928)
  at done (angular.js:11266)
  at completeRequest (angular.js:11464)
  at XMLHttpRequest.requestLoaded (angular.js:11405)

为什么?

5 个答案:

答案 0 :(得分:1)

您正尝试记录不存在的myData

试试这个

$http.get(url).then(function(response){
    // Will have proper data only if your response has the key 'records'. 
    // Otherwise your $scope.myData will have undefined value
    console.log(response.data) //Check if Key 'records' is present.

    $scope.myData = response.data.records;
    console.log($scope.myData.name);
});

答案 1 :(得分:0)

myData未定义..

使用$scope.myData获取输出。

答案 2 :(得分:0)

错误是您在response.data.records的{​​{1}}回调中引用了success。您的json将直接在then上提供。所以你需要做的只是访问

response.data

答案 3 :(得分:0)

var app = angular.module('myAppp', []);
app.controller('customersCtrl', function($scope, $http) {
angular.element(document).ready(function(){
$scope.myData={};
});
$http.get('data.json').then(function (response) {
$scope.myData = response.data.records;
console.log($scope.myData ); //make sure this is not null/undefined
console.log($scope.myData.name); //if not null this will work
});
});

答案 4 :(得分:-1)

尝试这个我认为这可能对你有用

myData[0].name