如何创造承诺?

时间:2015-07-30 07:33:06

标签: angularjs

问题是$ window.print()总是被调用,而不仅仅是当promise成功时。如何在填充数据时创建promise?有什么建议吗?

'use strict';
angular.module("printModule").controller('printController', ['$scope', '$window', '$q', function ($scope, $window, $q) {


    $scope.ticketPin = localStorage.getItem("pin");
    $scope.payoutTime = localStorage.getItem("payoutTime");
    $scope.payoutAmount = localStorage.getItem("payoutAmount");

    var defer = $q.defer();
    defer.resolve($scope.ticketPin);
    defer.resolve($scope.payoutTime);
    defer.resolve($scope.payoutAmount);

    defer.promise.then(function () {
        $window.print();
    })
}]);

1 个答案:

答案 0 :(得分:1)

function getFromLocalStorage (item, callback)  {
    //To prevent errors
    if (callback) {
        return callback(localStorage.getItem(item)) ;
    }
} 

var callback;
callback = function (data) {
    //Set variable to data
} 

//I would make getFromLocalStorage a factory
myFactory.getFromLocalStorage("itemName", callback);

警告,上面应该能够工作但是我还没有使用LocalStorage来了解ins,out和gotchas,因此可能需要对嵌套返回进行一些重新排列。