【问题标题】:Angular View not updating after retrieving data from database从数据库中检索数据后角度视图未更新
【发布时间】:2015-06-13 21:25:07
【问题描述】:

我目前正在开发一个应用程序,该应用程序可检索有关 $routeParams 更改的数据。所以它是这样开始的:

function artistCtrl($scope, $http, $location, dataFactory, $routeParams){
$scope.artistName = $routeParams.artistname

$scope.$watch('artistName', function(newValue, oldValue){
  $scope.artistInfo = dataFactory.getArtist(newValue)
})

$scope.artistInfo = {
  artist_name: dataFactory.artistInfo.artist_name,
  artist_genre: dataFactory.artistInfo.artist_genre,
  artist_imageurl: dataFactory.artistInfo.artist_imageurl,
  artist_bio: dataFactory.artistInfo.artist_bio
};
}

$watch 的回调在这里运行。 dataFactory.getArtist 从我正在成功完成的数据库中检索newValue。这样做是这样的:

dataFactory.js

  dataFactory.getArtist = function(artist){   
    return dataFactory.checkDb(artist).then(function(dbData){
      if(dbData.data != "No data"){
          dataFactory.artistInfo = dbData.data[0] 
      } 
      return dbData.data[0]
    })
  }

dataFactory.artistInfo = "";

dataFactory 是我在另一个文件中创建的工厂。

artistpage.html

<div class="container this">
      <div class="row">
        <div class="col-sm-6">
          <div><h1>{{artistInfo.artist_name}}</h1></div>
          <div rate-yo id='stars' rating="myRating" class="col-sm-4"></div>
          <div id='reviews'>23 Reviews</div>
          <div><h2>{{artistInfo.artist_genre}}</h2></div>
          <div><p>{{artistInfo.artist_bio}}</p></div>
          <div><button type="button" class="btn btn-primary" ng-click="somefunc()">Submit a Review</button></div>
        </div>
        <div class="col-sm-6 reviews">
          <div><img class="artistpageimage" src={{artistInfo.artist_imageurl}}></div>
        </div>
      </div>

</div>

我不明白为什么我的视图没有更新。我试图通过分配返回的dataFactory.getArtist(newValue) 来更新 $scope.artistName 并且通过将新数据分配给dataFactory.artistInfo 我已经阅读了有关 $apply 的信息,但我很难弄清楚如何在这种情况下应用它。有人可以帮忙吗?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    getArtist 是否返回一个承诺或一个值。如果这是一个承诺,请尝试以下内容:

    $scope.$watch('artistName', function(newValue, oldValue){
      dataFactory.getArtist(newValue).then(function(value) {
        $scope.artistInfo = value;
      })
    })
    

    【讨论】:

      【解决方案2】:

      我认为问题在于dataFactory.getArtist(newValue) 正在返回一个承诺,您将其直接分配给artistInfo。尝试将其替换为:

      dataFactory.getArtist(newValue).then(function (info) {
          $scope.artistInfo = info;
      });
      

      【讨论】:

        猜你喜欢
        • 2020-12-17
        • 2015-06-26
        • 2017-10-03
        • 2015-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-03
        相关资源
        最近更新 更多