如何从angularjs中的object属性调用service方法?

时间:2014-07-17 06:08:05

标签: angularjs angularjs-scope

Angular Js对象:

$scope.Global = {
    brand: null,
    group: null,
    timeperiod: null,
    gender: $scope.Gender[0],
    segmenttype: $scope.SegmentType[0]
};

Angular Js服务方法:

dataFactory.getAllTimePeriods().success($scope.handleSuccess).then(function (result) {
        $scope.TimePeriods = result.data;
    });

我们可以将服务方法调用到对象属性吗?

像这样

$scope.Global = {
    brand: null,
    group: null,
    timeperiod:   dataFactory.getAllTimePeriods().success($scope.handleSuccess).then(function (result) {
        $scope.TimePeriods = result.data;
    });,
    gender: $scope.Gender[0],
    segmenttype: $scope.SegmentType[0]
};

1 个答案:

答案 0 :(得分:1)

正如Liad Livnat所说,你可以写

dataFactory.getAllTimePeriods().success($scope.handleSuccess).then(function (result) {
    $scope.Global = {
        brand: null,
        group: null,
        timeperiod: result.data;
        gender: $scope.Gender[0],
        segmenttype: $scope.SegmentType[0]
    };
}

如果您有多个承诺,可以像这样使用$ q.all

var promiseOne = dataFactory.getAllTimePeriods().success($scope.handleSuccess);
var promiseTwo = ...
var promiseThree = ...
$q.all([promiseOne, promiseTwo, promiseThree])
  .then(function(results) {

    $scope.Global = {
        brand: null,
        group: null,
        timeperiod: results[0].data;
        gender: $scope.Gender[0],
        segmenttype: $scope.SegmentType[0]
    };

    console.log(results[0], results[1], results[2]);
});

正如您所看到的,结果变量从数组中的promises中获取所有数据,您可以使用结果[0],结果[1]等访问它们。