0

我有一個使用Firebase的簡單應用程序。對於Firebase數據庫,我保存了一些數據,保存後我想向用戶顯示警報窗口,並提供「everythig很好」或「bad」的響應。對於使用ui-bootstrap的警報窗口。對於警報我使用$ rootScope。所以,當我存了一些數據我有所回調:

person.child(someName) 
        .set(personData) 
        .then(function() { 
        $rootScope.alert = {type:'success', msg:'Person is added!'}; 
         $rootScope.showAlert = true; 
        console.log($rootScope.showAlert, $rootScope.alert); 
        }) 
        .catch(function (e) { 
        $rootScope.alert = {type:'danger', msg:e}; 
        $rootScope.showAlert = true; 
        }); 

HTML是:

<div uib-alert 
    ng-class="'alert-' + (alert.type || 'warning')" 
    dismiss-on-timeout="2000" 
    ng-if="showAlert" 
    close="close()">{{alert.msg}} 
</div> 

<button ng-click='press()'>Press</button> 

和控制器調用工廠:

$scope.press = function() { 
    fact.setItem({name: 'Josh', age: 20, sex: 'male'}); 
} 

在控制檯中我看到rootScope是設定值警報和showAlert,但警報不起作用,所以我將這2個值綁定在html頁面上,並且我看到我第一次按下按鈕不起作用,但第二次正在工作等。In jsbin example I make this situation。在這種情況下我錯了?

回答

1

由於火力是第三方角度,$rootScope是沒有得到應用。

所以,你必須手動應用$rootScope,使其工作。

這裏是你的問題的解決方案。我會盡快找到另一個解決方案。

嘗試使你的工廠,

app.factory('fact', ['$firebaseArray', '$rootScope', function($firebaseArray, $rootScope) { 
    var person = firebase.database().ref().child('evil_genius'); 

    return { 

    setItem : function(personData) { 
     var someName = Math.random().toString(36).substring(7); 
       return person.child(someName) 
        .set(personData) 
        .then(function() { 
        $rootScope.alert = {type:'success', msg:'Person is added!'}; 
         $rootScope.showAlert = true; 
        $rootScope.$apply(); 
        console.log($rootScope.showAlert, $rootScope.alert); 
        }) 
        .catch(function (e) { 
        $rootScope.alert = {type:'danger', msg:e}; 
        $rootScope.showAlert = true; 
        }); 
    } 
    } 
}]) 

HERE IS A WORKING DEMO

+0

THX的答案,它的作品!我忘了$申請和幾天不明白什麼是錯的:) – YoroDiallo

1

試試這個:

.then(function() { 
    $rootScope.alert = {type:'success', msg:'Person is added!'}; 
    $rootScope.showAlert = true; 
    $rootScope.$apply(); 
}) 
.catch(function (e) { 
    $rootScope.alert = {type:'danger', msg:e}; 
    $rootScope.showAlert = true; 
    $rootScope.$apply(); 
}); 
+0

thx爲您的答案!有用! – YoroDiallo