【问题标题】:angularJS function in controller does not respond控制器中的angularJS函数没有响应
【发布时间】:2014-02-19 17:44:57
【问题描述】:

AngularJs ng-click 没有响应

我正在尝试使用 GitHub Search-API。 当有人单击按钮时,我的控制器应该从 github 调用搜索,这是我的代码

HTML:

<head>
  <script src="js/AngularJS/angular.min.js"></script>
  <script src="js/Controller/RepoController.js"></script>
</head>
<body ng-controller="RepoController">
 <input type="text" ng-model="param" /><button ng-click="search()">suchen</button>
  <ul>
    <li ng-repeat="repo in repos">
        {{repo.name}}
    </li>
  </ul>
 
</body>

这是我的控制器:

var App = angular.module('RepoSearch', []);
 
function RepoController($scope, $http) {
    $scope.repos = [];

    $scope.search = function() {
        $http.get('https://api.github.com/search/repositories?q='+$scope.param).success(function(data) {
            $scope.repos = data['items'];
        }
    }
 
}

但我的 repos-array 仍然是空的 当我将$http.get 与警报交换时,它工作正常。

【问题讨论】:

    标签: javascript json angularjs


    【解决方案1】:

    您忘记在$scope.repos = data['items'];} 之后关闭(,并定义ng-app,在这种情况下,可以在&lt;head&gt; 中:&lt;head ng-app="RepoSearch"&gt; http://docs.angularjs.org/api/ng.directive:ngApp

    【讨论】:

    • 我在我的 html 标签中定义了 ng-app,但我无法处理将其插入代码部分:D
    【解决方案2】:

    原因可能是跨域调用。使用 JSONP 调用 github。

    $http.jsonp('https://api.github.com/search/repositories?q='+$scope.param+'&callback=JSON_CALLBACK'+).success(function(data) {
                $scope.repos = data['items'];
    }
    

    回调方法可能不同,请查看这些 SO 帖子

    Using angularjs JSONP when callback cant be defined

    Using JSONP method for $http service in AngularJS

    【讨论】:

      【解决方案3】:

      在 HTML 中

      <head ng-app="RepoSearch">
            <script src="js/AngularJS/angular.min.js"></script>
            <script src="js/Controller/RepoController.js"></script>
          </head>
          <body ng-controller="RepoController">
           <input type="text" ng-model="param" /><button ng-click="search()">suchen</button>
            <ul>
              <li ng-repeat="repo in repos">
                  {{repo.name}}
              </li>
            </ul>
      
          </body>
      

      在控制器中

      var App = angular.module('RepoSearch', []);
      
      
      //bind controller with your app
      
      App.controller('RepoController',RepoController);
      
      function RepoController($scope, $http) {
          $scope.repos = [];
      
          $scope.search = function() {
              $http.get('https://api.github.com/search/repositories?q='+$scope.param).success(function(data) {
                  $scope.repos = data['items'];
              }
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2015-05-03
        • 1970-01-01
        • 1970-01-01
        • 2018-06-18
        • 2023-04-03
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多