无法在bootstrap模式中以角度访问$ http数据

时间:2015-08-19 13:30:13

标签: angularjs angular-ui-bootstrap

我已经使用过搜索功能,但我没有找到解决问题的解决方案。 我在Angular中使用UI Bootstrap指令。在打开模态之前,我想进行$ hhtp get调用以获取模态的数据。几乎所有东西都完美无缺,除了第一次打开模态中没有数据。当我再次点击时,数据存在。

这是我的代码:

myapp.controller( 'jobsController', [ '$rootScope', '$scope', '$http', '$modal', function( $rootScope, $scope, $http, $modal ) {

    $scope.post = [];

    $scope.getJobs = function(id) {

        $http({
            method: 'GET',
            url: $scope.api,
            params: {
                'type' : 'jobs',
                'filter[p]' : id,
                'filter[post_status]' : 'publish'
            }
        }).
        success( function( data ) {
            $scope.post = data[0];
        });

    };

    $scope.open = function(id) {

        $scope.getJobs(id);

        $scope.opts = {
            backdrop: true,
            keyboard: true,
            backdropClick: true,
            scope: (function () {
                var scope = $rootScope.$new();
                scope.post = $scope.post;
                return scope;
            })(),
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl'
        };
      
        $modal.open($scope.opts);
    };

}]);

myapp.controller('ModalInstanceCtrl', ['$scope', '$modalInstance', function ($scope, $modalInstance) {
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
}]);

我已尝试过本网站和其他网站的几个教程和代码片段,但我没有找到解决方案。任何帮助都会非常感激。

很多

1 个答案:

答案 0 :(得分:0)

$ http.get是异步调用。在访问数据之前,呼叫需要“返回”。

$scope.getJobs = function(id) {

    return $http({
        method: 'GET',
        url: $scope.api,
        params: {
            'type' : 'jobs',
            'filter[p]' : id,
            'filter[post_status]' : 'publish'
        }
    });

};

$scope.open = function(id) {

    $scope.getJobs(id).
    then( function( data ) {
        $scope.post = data[0];

        $scope.opts = {
          backdrop: true,
          keyboard: true,
          backdropClick: true,
          scope: (function () {
            var scope = $rootScope.$new();
            scope.post = $scope.post;
            return scope;
          })(),
          templateUrl: 'myModalContent.html',
          controller: 'ModalInstanceCtrl'
        };

        $modal.open($scope.opts);

    });
};

因此,为了使其有效,最简单的方法是在open函数内处理承诺的解决方案。

PS:你的代码有效,但不是真正的角度风格,也没有效率。

  • 您无需将所有对象放在$ scope中。如果您只需要在控制器中使用它们,也可以创建局部变量。
    例如:

    $ scope.opts = {};

可以替换为:

var opts = {};

这将阻止角度每次$digest()

检查变量的值
  • 将您的服务器调用委托给服务。您将能够在控制器之间共享呼叫。

  • 如果可能,请使用controller as语法。

请不要犹豫,阅读此风格指南:https://github.com/johnpapa/angular-styleguide

相关问题