如何在范围内节省服务价值?

时间:2015-02-17 12:55:50

标签: angularjs


您好, 我试图在控制器中使用服务值(JSON)并转到另一个视图:

.controller('TrainCtrl', function ($scope, $sce, $state, medias) {

    $scope.train = function(id){
        medias.getMedias().then(function(message){
            $scope.movie = message.training;
            // Object {id: 1, title: ""...}
            console.log($scope.movie);
        });
        // undefined
        console.log($scope.movie);
        // View is empty because $scope.movie is undefined
        $state.go('training');
    };})

    .factory('medias', function($http, $log, $q){
    return{
        getMedias: function(){
            console.log('getMedias');
            var deferred = $q.defer();
            $http.get('js/medias.json')
            .success(function(data){
                deferred.resolve(data);
            })
            .error(function(msg, code){
                deferred.reject(msg);
                $log.error(msg,code)
            });
            return deferred.promise;
        }
    }
});

如何保存在指令中重定向的控制器中使用的服务结果?

我的杰森:

{"training" :
{"id" : 1,
"url": "http://player.vimeo.com/external/85569724.sd.mp4?s=43df5df0d733011263687d20a47557e4",
"content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim",
"type": "video/mp4"
}

}

它也不起作用:

$scope.train = function(id){
    medias.getMedias().then(function(message){
        //$scope.movie = message.training;
        $scope.movie={
        url: $sce.trustAsResourceUrl("http://player.vimeo.com/external/85569724.sd.mp4?s=43df5df0d733011263687d20a47557e4"),
        content: 'Lorem ipsum dolor sit amet',
        type: 'video/mp4'
    };
        $state.go('training');
    });

};

THX

1 个答案:

答案 0 :(得分:0)

让我们谈谈异步性......

$scope.train = function(id){

    medias.getMedias().then(function(message){
        //This is async callback
    });
    // ! This is normal execution, calling movie syncronously, movie is not yet defined !
    console.log($scope.movie);
    $state.go('training');
};})

在http get之后调用.then,可以在程序执行期间随时调用它。为了工作,您应该将所有内容都放在.then

$scope.train = function(id){
    medias.getMedias().then(function(message){
        $scope.movie = message.training;
        // Object {id: 1, title: ""...}
        console.log($scope.movie);
        // undefined
        console.log($scope.movie);
        // View is empty because $scope.movie is undefined
        $state.go('training');
    });
};})

Angular会相应地更新视图。