javascript - $http 变量范围问题

标签 javascript angularjs

$http({
    url: "php/myuId.php",
    method: "POST",
    data: {
        'userId': userId,
    },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, headers, config) {

        $scope.myId= data;
//return last inserted id
    }).error(function(data, status, headers, config) {
    });
//can't use it outside?
        $scope.user.push({
        "userId":  $scope.myId,

    });

奇怪的是,当我在 $http 范围之外使用 $scope.myId 时,它并没有改变,所以我无法将最后插入的 id 推送到前端。

最佳答案

问题在于它是异步的,因此在 promise 返回之前您还没有数据。您可以将 $scope.user.push 放入成功回调中,或者使用 $scope.$watch("myId"... 在值更新时进行注册。

关于javascript - $http 变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23464350/

相关文章:

javascript - 动态创建 HTML 元素

javascript - 使用点击事件在控制台日志中显示响应

javascript - 防止退格键在 AngularJS 中导航回来

angularjs - 使用 ng-repeat 切换菜单

javascript - AngularJS 从不良数据中过滤掉字符串。

javascript - 多个div跨越父级的高度

javascript - 使用 AJAX 输入类型 ="submit"而不是输入类型 ="button"?

php - 我可以同时提交两份表格吗?

javascript - data-ng-show 和数组元素

javascript - 如何使用jQuery从 Angular outerHtml获取所选选项的innerText?