8

我正在尝试制作一个小通知器,通知典型情况:需要授权,保存更改等。通知显示 3 秒并消失,如果用户没有点击它(如果点击了通知,它会立即消失)。文档不是很丰富。我应该如何使用,在 3 秒后$timeout调用?close();以及如何将变量(nId)放入函数中?我尝试(*function(){return function(){}}*)在 default中关闭setTimeOut(),但没有成功。

myApp.controller('noticesCtrl',
    function noticesCtrl($scope, $rootScope, noticesData){
        $rootScope.notices = [];
        $scope.closeNotice = function(nId){
            noticesData.close(nId);
        };
    });

myApp.factory('noticesData', function($rootScope, $timeout){
    return{
        add: function(type, text){
            var nId = $rootScope.notices.length + 1;
            $rootScope.notices.push({id: nId, type:type, text:text+nId});
            // call close function with 3sec. delay; how?
        },
        close: function(nId){
            angular.forEach($rootScope.notices, function(notice, key){
                if(notice.id == nId){
                    $rootScope.notices.splice(key,1);
                }
            });
        }
    }
});
4

2 回答 2

4
myApp.factory('noticesData', function($rootScope, $timeout){
    var obj = {};
    obj.add = function(type, text){
        var nId = $rootScope.notices.length + 1;
        $rootScope.notices.push({id: nId, type:type, text:text+nId});
        $timeout(function(){
            obj.close(nId);
        },3000);
    }
    obj.close = function(nId){
        angular.forEach($rootScope.notices, function(notice, key){
            if(notice.id == nId){
                $rootScope.notices.splice(key,1);
            }
        });
    }
    return obj; 
});
于 2013-09-09T06:41:56.967 回答
-2

这是怎么做

$timeout(function () {

    // do something

}, 50);
于 2015-02-18T13:36:03.313 回答