星期二, 7月 22, 2014

[AngularJS] 初學者的angular常用語法筆記

最近重回NG的懷抱,
從邊做專案的過程中,
記錄一些常用的手法。避免會忘記XD

ng-class

//設定某個物件被選擇
 ng-class="{true: 'table-row-selected', false: ''}[product.selected]"

Filter

//取得被選擇的使用者數量
  $scope.getSelectedUsers = function() {
   var selectedObjs = $filter("filter")($scope.userList, {
    selected: true
   })
   return selectedObjs;
  };

陣列反轉

//html 
ng-repeat="folder in parentFolders.slice().reverse()


改變url上面的參數

$location.path('/login');

轉頁

$window.open('http://www.yahoo.com.tw');

如果從已知的array移除指定的item

$scope.userList.splice($index, 1);//移除使用者清單內的某一用戶

事件處理$broadcast, $emit, $on


$broadcast:
發送事件的方法,向下分派事件到所有的子scope範圍。此外也可以由$rootScope發送事件,但要慎用。

$emit:
發送事件的方法,向上分派事件到scope階層範圍。

$on 接受事件的方法,發送端可帶入參數至接收端


將$http request加入common的header

由於REST API很流行,大家都會定義呼叫時要帶入application/json,做法如下。
app.run(['$http', function($http) {

// The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

// $httpProvider.defaults.headers.common (headers that are common for all requests):
// Accept: application/json, text/plain, * / *
// $httpProvider.defaults.headers.post: (header defaults for POST requests)
// Content-Type: application/json
// $httpProvider.defaults.headers.put (header defaults for PUT requests)
// Content-Type: application/json


 $http.defaults.headers.common['Content-Type'] = 'application/json';
}])


$http GET content-type header無法正確送出的解決方法

[AngularJS] $http無法送出 content-type header

如何使用$watch監控JSON 物件

Call $watch with true as the third argument:
 
$scope.$watch('form', function(newVal, oldVal){
    console.log('changed');
}, true);

By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal. Per the Angular documentation, the third parameter is for objectEquality: When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails