[Firebase] 2. Firebase Event Handling

/**
 * Created by Answer1215 on 11/9/2014.
 */

var app = angular.module('app', ['firebase']);

app.constant('FIREBASE_URI', 'https://zhentiw-angular-fire.firebaseio.com/');

app.controller('MainCtrl', ['$scope', 'ItemsService', function ($scope, ItemsService) {
    $scope.newItem = { name: '', description: '', count: 0 };
    $scope.currentItem = null;
    $scope.isUpdated = false;

    $scope.items = ItemsService.getItems();

    $scope.items.$on('change', function(){
        if(!$scope.isUpdated){return;}
        console.log("ITEMS CHANGE");
    });

    $scope.items.$on('loaded', function(){
        console.log("ITEMS LOADED");
    });

    //Deattach the change event from the items
    //$scope.items.$off('change');


    $scope.addItem = function () {
        ItemsService.addItem(angular.copy($scope.newItem));
        $scope.newItem = { name: '', description: '', count: 0 };
    };

    $scope.updateItem = function (id){
        $scope.isUpdated = true;
        ItemsService.updateItem(id);
    };

    $scope.removeItem = function (id) {
        ItemsService.removeItem(id);
    };
}]);

app.factory('ItemsService', ['$firebase', 'FIREBASE_URI', function ($firebase, FIREBASE_URI) {
    var ref = new Firebase(FIREBASE_URI);
    var items = $firebase(ref);

    var getItems = function () {
        return items;
    };

    var addItem = function (item) {
        items.$add(item);
    };

    var updateItem = function (id) {
        items.$save(id);
    };

    var removeItem = function (id) {
        items.$remove(id);
    };

    return {
        getItems: getItems,
        addItem: addItem,
        updateItem: updateItem,
        removeItem: removeItem
    }
}]);

 

You can lisisten to the 'loaded', 'chane' events by using

  $on('loaded', function(){...}).

You can deattache the events by using 

  $off()  //unattach all events

  $off('loaded') //unattach only loaded event

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值