顯示具有 AngularJS 標籤的文章。 顯示所有文章
顯示具有 AngularJS 標籤的文章。 顯示所有文章

2014年3月11日 星期二

[Javascript] AngularJS 與 img src & img ng-src

用 AngularJS 在處理 img 時,沒看手冊的用法:

<img src="{{item.url}}" />

雖然網頁顯示一切正常,但仔細看 Google Chrome 開發人員工具時,發現有奇怪的 requests 發出去,是的,發出去的資料就是 http://hostname/%7B%7Bitem.url%7D%7D ,解法就是改用 ng-src 吧!

<img ng-src="{{item.url}}" />

AngularJS 官方文件 ngSrc :

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

2014年3月4日 星期二

[Javascript] 偵測 AngularJS rendered a template - 以 Google Visualization API 應用為例

用 AngularJS MVC 架構時,想撈出資料後,再動態用 Google Visualization API 繪出資料。然而,在 AngularJS 架構下,不該怎樣偵測它已經完成呈現部分(rendered a template),依照原理,只好看看何時能取得到某物件(document.getElementById("tag_id"))。

Javascript:

(function(){

$scope.$watch(function(){
return document.getElementById(tag);
},function(value){
var val = value || null;
if(val) {
// doing...
}
});
})();


HTML:

<body ng-controller="appControl">
<div ng-repeat="item in data" id="{{item.id}}">{{item.id}}</div>
</body>


由於 <DIV> 是依照 AngularJS 架構產生的,而 Google Visualization API 需要綁定在某個 div 物件上,因此才需要去偵測 AngularJS 到底將 div 呈現出來了沒。

範例:

<script type='text/javascript' src='//www.google.com/jsapi'></script>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js'></script>
<script type='text/javascript'>

google.load('visualization', '1', {'packages': ['corechart']});

function appControl($scope, $http, $location) {
$scope.data = null;
$scope.query = function() {
$http.get('/api', {}).success(function(data){
$scope.data = data;
for( var i=0 ; i<data.length ; ++i ) {
(function(){
var job_id = data[i]['id'];
var job_title = data[i]['title'];
var job_data = data[i]['data'];

$scope.$watch(function(){
return document.getElementById(job_id);
}, function(value) {
var check = value || null;
if(check) {
var data = new google.visualization.arrayToDataTable(job_data, true);
var options = { title: job_title, is3D: true };
//var chart = new google.visualization.PieChart(document.getElementById(job_id));
var chart = new google.visualization.PieChart(check);
chart.draw(data, options);
}
});
})();
}
}).error(function(data){
});
};
$scope.query();
}

</script>