value $ scope未定义

时间:2017-04-03 13:01:24

标签: javascript angularjs scope

我有2个文件。第一个:

<script>
var demo=angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
     $http.get('http://localhost/scores').then(function(response) {
     $scope.scores = response.data;         
    });
    });
</script>

另一个文件index.html

    

 <head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="scoresCtrl.js"></script>
     <script> 
            function run(){ 
                var data=angular.element(document.getElementById("scoresBodyId")).scope().scores;
                alert(data);
            }
     </script></head>

<body  onload="run()" id="scoresBodyId" ng-controller="scoresCtrl" >
</body>

当我尝试显示提醒(数据)时,我未定义 但当我用 onclick 替换 onload 时,点击后我获得了我的值。
我想使用onload。感谢您的解释和帮助。

1 个答案:

答案 0 :(得分:0)

您需要将onload更改为ng-init才能在正文上调用您的功能

控制器

var demo = angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
    $scope.run = function() {
        $http.get('http://localhost/scores').then(function(response) {
            $scope.scores = response.data;
            alert($scope.scores);
        });
    }
});

的index.html

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="scoresCtrl.js"></script>
</head>

<body ng-init="run()" id="scoresBodyId" ng-controller="scoresCtrl">
</body>