$ http.get的角度问题

时间:2016-04-18 15:54:50

标签: angularjs search http-get

我刚刚开始学习Angular,我在根据http-get请求检索数据时遇到问题。当我只是检索所有电影时它会起作用,但是当我尝试根据搜索词检索电影时(cfr。 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>

1 个答案:

答案 0 :(得分:1)

替换

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;
    });