javascript - 在 http.get 回调中访问 $scope 日期

标签 javascript angularjs

我需要将 $http.get 返回的数据存储在 $scope 变量中,以供我的 ui-grid 控件使用.

我确信我错过了一些非常简单的东西,但我找不到什么。这是我的代码:

app.controller('AdminUsersGridCtrl', function ($scope, $http, uiGridConstants) {

    $http.get('/api/admin/user')
    .success(function (response, $scope) {
        $scope.myData = response;
    })
    .error(function (error) {
        console.log(error);
    });

    console.log($scope.myData);

    $scope.gridOptions = {
      data: 'myData',
      enableFiltering: true,
      columnDefs: [
        { field: 'firstName' },
        { field: 'lastName' },
        { field: 'jobTitle'},
        {
          field: 'email',
          filter: {
            condition: uiGridConstants.filter.ENDS_WITH,
            placeholder: 'ends with'
          }
        },
        {
          field: 'phone',
          filter: {
            condition: function(searchTerm, cellValue) {
              var strippedValue = (cellValue + '').replace(/[^\d]/g, '');
              return strippedValue.indexOf(searchTerm) >= 0;
            }
          }
        },
      ]
    };        

  });

我的控制台成功打印未定义。如何访问 $http.get success 函数中的原始 $scope

最佳答案

My console inside success prints undefined

但是,您的控制台不在 success 方法内。这是里面的:

$http.get('/api/admin/user')
.success(function (response) {
    $scope.myData = response;
    console.log($scope.myData);
})
.error(function (error) {
    console.log(error);
});

这不是:

// order of events..
// #1...first $http
$http.get('/api/admin/user')
.success(function (response) {
    //... #3 third. Now finally response is defined. the end
    $scope.myData = response;
})
.error(function (error) {
    console.log(error);
});

//... #2 second. $scope.myData definitely IS undefined
console.log($scope.myData);

巨大的差异。也无需在成功回调中包含 $scope。我以前从未见过这样的情况。你从哪里得到的?

关于javascript - 在 http.get 回调中访问 $scope 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601458/

相关文章:

javascript - 将键和值动态插入 json 数组结构

javascript - 我可以在 Angular 模板中声明一个简单的函数吗?

angularjs - 如何添加 angularJs 表达式 {{}} 作为函数参数

javascript - 如何在小屏幕和大屏幕上将通知图标与菜单切换贴在一起?

javascript - 浏览器有可能不兼容JQuery吗?

javascript - 使用数组值将数组转换为不同的结构

javascript - 简单求和 ng-repeat 列

javascript - 如何在 Bootstrap 中使用 img-circle 图像在悬停时添加标题

javascript - 访问 Controller 中的 $rootScope 方法

javascript - AngularJS - 在模块依赖注入(inject)时加载 vendor 脚本