使用 AngularJS 显示"Add to Wishlist"通知的最佳方法



>场景:我想在将产品添加到愿望清单后向用户显示通知

我已经实现了这段代码及其工作,但我想知道使用角度特征执行此操作的最佳方法。我为此使用了$rootScope。下面是代码:

在控制器中

$scope.addToWish = function (product) {
    var user = checkUserLoginStatus.getIsUserLoggedin();
    if (user == ""){
        $('#ModalLogin').modal();
    }else {
            DataRepository.saveProductsToWishList(product); // service
            $scope.$watch($rootScope.addedToWishList, function () {
               $timeout(function() {
                 $rootScope.addedToWishList = false;
                }, 4000);  // to hide alert after 4 secs
            });
    }
}

DataRepository服务中,我正在更新$http成功函数的值

$http({
   // Some POST call
 })
 .success(function (response)
   {
     $rootScope.addedToWishList = true;  // this makes ng-show true on html
     $rootScope.$emit('WishList modified', response);
   })

如果您从 DataRepository 返回 $http 调用,则可以像这样将.then链接到它:

控制器:

$scope.addToWish = function (product) {
    var user = checkUserLoginStatus.getIsUserLoggedin();
    if (user == ""){
        $('#ModalLogin').modal();
    } else {
        DataRepository.saveProductsToWishList(product)
            .then(function() {
                // show wishlist message
                $scope.wishlistMessage = "Added to wishlist";
                $timeout(function() {
                    // hide wishlist message
                    $scope.wishlistMessage = "";
                }, 4000);
            });
    }
}

服务

function saveProductsToWishList(product) {
    return $http({
        // some post call
    });
}

一般来说,你希望远离rootScope。

最新更新