[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

posted @   Zhentiw  阅读(220)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示