Angular $http.get 有问题

Angular trouble with $http.get

我刚开始学习 Angular,但我无法根据 http-get 请求检索数据。当我简单地检索所有电影时它起作用,但当我尝试根据搜索词检索电影时它不起作用(参见 search.html)。希望有人能告诉我哪里错了,我实在是看不出来。提前谢谢你。

app.js:

var app;

(function() {

  app = angular.module('imdb', ['ngRoute']);

  app.config(function($routeProvider) {
    $routeProvider
      .when('/search', {
        controller: 'SearchController',
        templateUrl: 'views/search.html' 
      })
      .when('/movies', {
        controller: 'MovieController',
        templateUrl: 'views/movies.html' //works fine
      })
      .otherwise({
        redirectTo: '/movies'
      });
  });
})();

SearchController.js

(function (app) {

  app.controller('SearchController', ['$http', '$scope', function ($http, $scope) {
    $scope.movies = [];

    $scope.searchMovie = function(title) {
      $http.get('https://angularbackend.azurewebsites.net/api/Movies/Search?title=' + title)
        .success(function(data) {
          $scope.movies = data;
        });
    };
  }]);
})(app);

search.html

<div>
  <form class="form" novalidate name="searchMovies" ng-submit="SearchController.searchMovie(title)" >
    <input type="text" ng-model="title" class="form-control" placeholder="enter title">
    <button type="submit" class="btn btn-primary btn-block">Search</button>
  </form>
  <table class="table">
    <thead>
    <tr>
      <th>poster</th>
      <th>title</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="movie in movies">
      <td>{{ movie.title }}</td>
    </tr>
    </tbody>
  </table> 
</div>

替换

SearchController.searchMovie(title)

来自

searchMovie(title)

所有表达式总是在范围内求值。所以第一个,不正确的,将尝试调用 $scope.SearchController 的方法 searchMovie,它不存在。

另请注意,success() 现在已被弃用很长一段时间了。使用 then():

$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search?title=' + title)
    .then(function(response) {
      $scope.movies = response.data;
    });

您还应该避免使用字符串连接来传递参数。这些需要正确编码。所以宁愿使用

$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search', {params: {title: title}})
    .then(function(response) {
      $scope.movies = response.data;
    });