无法在 bootstrap 模态中访问 angular 中的 $http 数据

Can't access $http data in angular in bootstrap modal

我已经使用了搜索功能,但是没有找到解决我问题的方案。 我在 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');
    };
}]);

我尝试了本网站和其他网站的一些教程和代码片段,但没有找到解决方案。任何帮助将不胜感激。

非常感谢

$http.get 是一个异步调用。在访问数据之前调用需要"come back"。

$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 :您的代码有效,但不是真正的 angular 样式,也不是高效的。

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

    $scope.opts = {};

可以替换为:

var opts = {};

这将防止 angular 每次检查变量的值 $digest()

  • 将您的服务器调用委托给服务。您将能够在控制器之间共享您的通话。

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

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