Angular - 从工厂获取数据

时间:2014-05-30 19:57:59

标签: angularjs angularjs-scope

我正在修改应用获取数据的方式。

该应用最初在页面上加载了数据

<script>
    var entries = <?php echo $this->entriesData; ?>;
</script>

然后在角度控制器中

$scope.entries = entries;

需求已更改,以便用户能够前进或后退一周,因此我在应用程序中添加了一个工厂,该工厂应该在页面加载时加载数据,然后在触发changeweek()时刷新数据。根据控制台,工厂(loadData)在页面加载时触发,然后再在changeweek()上触发,并且数据按预期从服务器中下载。问题是视图不显示数据。我假设我没有正确地将数据返回到$ scope.entries。求救!

var timeEntry = angular.module('timeEntry', ['ui.select2']);

timeEntry.factory('loadData', function($http){
    var url = 'index/getentries';
    var returnData = '';
    var factory = {};
    factory.getData = function(sDate, eDate){
        $.post(url, {week_start: sDate, week_end: eDate})
        .done(function(json, textStatus){
            if (textStatus === 'success') {
                returnData = json;
            }else{
                // handle fail
            }
        })
        .fail(function(){})
        .always(function(){});
        return returnData;
    };
    return factory;
});

timeEntry.controller('timeEntryController', ['$scope','loadData', function ($scope, loadData) {
    $scope.loading = true;

    $scope.date           = [];
    $scope.date.start     = startDate;
    $scope.date.end       = endDate;

    $scope.entries = loadData.getData($scope.date.start, $scope.date.end);

    $scope.weekTotal      = 0;
    $scope.timeEntryError = [];

    $scope.$watch('entries', function(newNames, oldNames) {
        $scope.dataCount = newNames.length;
        $scope.timeEntryError = [];
        calculateTotals();
        checkDayHours();
        checkSpecialDays();

    }, true);

    $scope.changeWeek = function(change) {
        sdate = moment($scope.date.start);
        edate = moment($scope.date.end);
        $scope.date.start = sdate.add(moment.duration(change, 'week')).format('YYYY-MM-DD');
        $scope.date.end   = edate.add(moment.duration(change, 'week')).format('YYYY-MM-DD');
        $scope.entries = loadData.getData();
    };
}]);

0 个答案:

没有答案