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

时间:2018-04-10 18:39:48

标签: angularjs angularjs-routing

所以,我有一点问题。我做了一个使用omdb api的小型webapp。问题是,当我输入我正在搜索的电影然后按搜索按钮时,视图应该更改为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>

1 个答案:

答案 0 :(得分:0)

在我们分解你看到的问题之前,只需几点说明。看起来你并没有充分利用angularjs。使用jquery和angularjs的混合不是最佳实践,并且可能使调试非常困难。我建议将movieTitle设为ng-model,并使用内置form validation的angularjs。这将允许您在控制器中轻松访问movieTitle,并利用angular的内置表单控制器和操作。

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

home.html文件中,我们会将ng-model添加到输入中,以便更加友好。现在,我们可以使用movieTitle访问控制器中的$scope.movieTitle。我也正在更改应该在提交到search()的{​​{1}}方法时运行的方法。

<强> home.html的

filmController

<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> 中,我会添加$location并将filmController方法移至getData()。我们现在将在表单提交上调用resultController,然后使用search()将视图切换到结果视图,将影片标题附加为路径参数,以便我们可以在$location中访问它。 / p>

<强> filmController.js

resultController

在新创建的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.js

resultController

最后,您需要更新自己的应用配置,让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