api 在 Angularjs 中获取数据时更新视图

Update view when api get data in Angularjs

所以,我有一个小问题。我制作了一个使用 omdb api 的小型 Web 应用程序。事情是这样的,当我输入我正在搜索的电影然后按下搜索按钮时,视图应该更改为 result.html 视图并显示我从 api 获得的数据。

api 工作正常。我得到了要显示的数据,但那是在我的 index.html 中。现在我已经使用 ng-routes

拆分了文件

如果你想看的话,我可以给你整个项目。也许我可以将它上传到某处的在线编辑器?

这是我的app.js

var myApp = angular.module("myApp", ['ngRoute']);

myApp.config(['$routeProvider', function ($routeProvider) {
  $routeProvider.
  when('/home', {
    templateUrl: 'views/home.html',
    controller: 'filmController'
  }).
  when('/result', {
    templateUrl: 'views/result.html',
    controller: 'filmController'
  }).otherwise({
    redirectTo: '/home'
  })
}]);


myApp.controller("filmController", function filmController($scope, $http, $window) {
  $scope.getData = function () {
    var movieTitle = document.getElementById("filmName").value;

    var binding = document.getElementsByClassName("ng-binding");

    $http
      .get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
      .then(function (response) {
        var data = response.data;

        if (data.Error) {
          alert("Film inte funnen");
          return false;
        }

        for (let key in data) {
          if (data.hasOwnProperty(key)) {
            let element = data[key];
            if (element === "N/A") {
              data[key] = "Inget hittat";
              if (key === "Poster") {
                $scope.post = "Ingen poster hittad";
              }
            }
            $scope.url = data;
          }
        }

        if (data.Ratings.length === 0) {
          $scope.rate = "Ingen utmärkelse/er hittad";
        }
        // This api data is printed to the console on the index.html view, i want it in the result view...
        console.log(data);

      });
  };
});

这是我的index.html

<body>
  <div class="main-content">
    <!-- <div class="container">
      <div class="row">
        <div ng-controller="MyController">
            <div ng-repeat="item in larare" class="col-lg-12">
              <div class="card">
                <img ng-src="/images/{{item.shortname}}.jpg" alt="Bild på {{item.name}}" class="card-img-top">
                <div class="card-body">
                  <h3 class="card-title">{{item.name}}</h3>
                  <p class="card-text">{{item.reknown}}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div> -->

    <header ng-include="'header.html'"></header>

    <main ng-view></main>

    </div>


  </div>
  <script>
    var elem = document.getElementsByTagName("body")[0];
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
      console.log("Nu");
    } else {
      console.log("Error");
    }

    function updateSite(event) {
      window.applicationCache.swapCache();
    }
    window.applicationCache.addEventListener('updateready',
      updateSite, false);
  </script>

  <script src="./js/formvalidation.js"></script>
</body>

</htm>

以及我的结果视图

<div class="show container" ng-show="url.Title">
<div class="poster">
  <!-- <img ng-src="{{ url.Poster }}"  alt="" /> -->
  <img ng-src="{{ url.Poster == 'Inget hittat' ? './images/image_not_found.png' : url.Poster }}">
  <p class="text-dark">{{ post }}</p>
</div>
<h2 class="text-dark">{{ url.Title | uppercase}}</h2>
<div class="movie-info">
  <p class="text-dark">
    <strong>Från:</strong> {{ url.Year }}</p>
  <p class="text-dark">
    <strong>Rating:</strong> {{ url.Rated }}</p>
  <p class="text-dark">
    <strong>Utgiven:</strong> {{ url.Released }}</p>
  <p class="text-dark">
    <strong>Längd:</strong> {{ url.Runtime }}</p>
</div>
<p class="text-dark">
  <strong>Skådespelare:</strong> {{ url.Actors }}</p>
<p class="text-dark">
  <strong>Regissör:</strong> {{ url.Director }}</p>
<p class="text-dark">
  <strong>Utmärkelser:</strong> {{ url.Awards }}</p>
<p class="text-dark">
  <strong>Handling: </strong> {{ url.Plot }}</p>
<h4 class="text-dark">
  <strong>Utmärkelser</strong>
</h4>
<p class="text-dark ">{{ rate }}</p>
<div ng-repeat="rating in url.Ratings | orderBy: '-Value'">
  <p class="text-dark">
    <strong>{{ rating.Source + ': ' + rating.Value }}</strong>
  </p>
</div>

这是我家的风景

<section class="text-white">
<img src="./images/background.jpg" alt="Bild på poster från Frankenstein filmen" class="bg-image">
<div class="main container align-middle">
  <div class="row text-center justify-content-center section-intro">
    <div class="col-6 mb-5">
      <h1>Filmtipset</h1>
      <h5>Sök efter dina favortfilmer</h5>
    </div>
  </div>

  <form ng-submit="getData()">
    <div class="inputSearch mx-auto">
      <div class="row justify-content-center">
        <div class="col-8">
          <div class="form-group">
            <label for="filmName">Film</label>
            <input class="form-control" type="text" name="filmName" id="filmName" placeholder="Ex. Armageddon" autofocus>
          </div>

          <input type="submit" class="btn btn-primary btn-lg btn-block btn-info mt-5" onclick="validateForm()" ng-click="'#!/result'">
        </div>
      </div>
  </form>

在我们分解您遇到的问题之前,请注意几点。您似乎没有充分发挥 angularjs 的潜力。混合使用 jquery 和 angularjs 不是最佳实践,并且会使调试变得非常困难。我建议将 movieTitle 设为 ng-model, as well as using angularjs's built in form validation。这将允许您在控制器中轻松访问 movieTitle,并利用 angular 的内置表单控制器和操作。

至于将数据获取到您的其他页面,我会为该页面添加第二个控制器,然后从您的 filmController,您可以在更改视图时将电影标题作为路由参数传递。在您的 resultController 中,您可以从路由参数中获取电影标题,然后在初始化结果 page/controller.

时执行 api 调用

在您的 home.html 文件中,我们将向输入添加 ng-model 以更加 angularjs 友好。现在我们可以使用 $scope.movieTitle 在控制器中访问 movieTitle。我也在更改应该在提交时获得 运行 的方法到我添加到 filmController.

search() 方法

home.html

<form ng-submit="search()">
// ... your other html here
<input class="form-control" type="text" name="filmName" id="filmName" ng-model="movieTitle" placeholder="Ex. Armageddon" autofocus>

在您的 filmController 中,我将添加 $location 并将 getData() 方法移动到 resultController。我们现在将在表单提交时调用 search(),然后使用 $location 将视图切换到结果视图,将电影标题附加为路由参数,以便我们可以在 resultController 中访问它。

filmController.js

myApp.controller("filmController", function filmController($scope, $http, $location) {
    // ... other code you have

    // this will be what gets called after the user types a movie title
    $scope.search = function () {
        var title = $scope.movieTitle; // or using jquery(not recommended)
        // this will change location and will produce
        // the url: http://[yoursite]/result?movieTitle=title
        $location.path('/result').search({movieTitle: title});
    }
 });

在您新创建的 resultController 中,我们将获取该路由参数并使用它来搜索数据。

resultController.js

myApp.controller("resultController", function resultController($scope, $http, $routeParams) {

    // the getData method moved to this controller
    $scope.getData = function (movieTitle) {
        $http
            .get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
        // the rest of your code for getData here
    };

    // I like to make an init method to make it clear what we are initializing
    $scope.init = function () {
        // this will get the movieTitle from the /result?movieTitle=title part of your url
        var movieTitle = $routeParams['movieTitle'];
        // now we call the method you have that uses the omdb api
        // just modify it to accept the movie title as a param rather than finding it in the html
        $scope.getData(movieTitle);
     }
     // run init method
     $scope.init();
});

最后,您需要更新您的应用配置,让您的 result 路由使用我们添加的 resultController 而不是 filmController