2013-10-19 61 views
1

當我的ng頁面加載下面包含ng-repeat標記時,它會在填充迭代器之前呈現IMG標記,但由於沒有src值,因此會生成404 for部分src。Angular ng-repeat在填充迭代器之前呈現模板

<div ng-repeat="item in preview_data.items"> 
     <h4>{{item.title}}</h4> 
     <a href="http://www.youtube.com/watch?v={{item.id}}" target="_blank"><img src="{{item.thumb}}" /></a> 
    </div> 

然後我的控制器開始並使用正確的視頻列表填充它。

如何在控制器準備好數據之前停止HTML渲染?

頁由這條路叫:

app.config(function ($routeProvider, $locationProvider) { 
    $locationProvider.html5Mode(true); 
    console.log('config'); 
    $routeProvider.when("/", { 
     templateUrl: "/templates/createFeed.html", 
     controller: "CreateFeedController" 
    }); 
}); 

這就要求工廠獲得的視頻列表,從後端API預覽:

app.controller("CreateFeedController", function ($scope, $route, $sce, Preview) { 
    var keywords = decodeURIComponent($route.current.params.keywords); 
    $scope.preview_data = { 
     keywords: keywords 
    } 
    //pass parameters to web preview API 
    Preview.get(keywords, function (data) { 

     $scope.preview_data.items = data; 

    }); 


}); 
app.factory('Preview', function ($http) { 
    return{ 
     get: function (keywords, next) { 
      $http({method: 'GET', url: '/api/preview/', json:true, 
        params: {keywords: keywords}} 
      ).success(function (data) { 
        // prepare data here 
        //console.log(data); 
        next(data); 
       }); 
     } 
    }; 
}); 
+0

看看[SO這個問題] [1]。你可以使用ngClock或使用ng-bind。 [1]:http://stackoverflow.com/questions/20871185/angularjs-not-loading-on-chrome – Ashish

回答

3

您必須在img標籤使用ng-src指令,而不是普通src屬性。

從角API爲ng-src

瀏覽器會從網址提取與文字文本{{哈希}},直到角代替內表達{{哈希}}。 ngSrc指令解決了這個問題。

+0

這工作,但我感覺不好接受答案:)作爲@Maxim Shoustin有建築更健全的建議。 – metalaureate

+0

這是您的案例的正確答案。即使ng-cloak也不能解決404錯誤,但這是正確的選擇。 –

1

正如你所知道$http回報的承諾。因此你的工廠是異步的。

所以工廠應該是這樣的:

app.factory('Preview', function ($http, $q) { 

    return{ 
     get: function (keywords, next) { 

      var deferred = $q.defer(); 

      $http({method: 'GET', url: '/api/preview/', json:true, 
        params: {keywords: keywords}} 
      ).success(function (data) { 
         deferred.resolve(data); 
       }).error(function() { 
       deferred.reject("Error ..."); 
      }); 
      //Returning the promise object 
      return deferred.promise; 
     } 
    }; 
}); 

和控制器:

 Preview.get(keywords) // returns promise 
      .then(function (result) { 
       $scope.preview_data.items = result;       
      }, function (result) { 
       alert("Error: No data returned"); 
       }); 
+0

非常感謝您提供了這種精湛的建議。 – metalaureate

+1

你歡迎:)無論如何,我認爲'ng-src'在你的情況下是更好的解決方案。礦是更通用的 –