我如何访问在 Angular JS 的 .then() 中定义的$scope数组

How can i get access to a $scope array which is defined in .then() in Angular JS?

本文关键字:then 数组 scope 定义 Angular 何访问 访问 JS      更新时间:2023-09-26

这是我的控制器代码

 $http.get(config.url+'/api/employees-suggestion/??token=' + currentUser.token + '&filterEmployee='+ "10000191")
.then(function(response) {
    console.log(response);
       $scope.id_list = [
         {employeeName: 'Hello'},
       ];
       console.log("id_list="+$scope.id_list);
   }, function(response) {
       }
 )

我想获取"$scope.id_list"的值并在另一个外部JS文件中使用它(这是ionic自动完成的自定义指令)。这是指令代码,

    angular.module('autocomplete.directive', [])
 .directive('ionicAutocomplete',
    function ($ionicPopover) {
      var popoverTemplate = 
       '<ion-popover-view style="margin-top:5px">' + 
         '<ion-content>' +
             '<div class="list">' +
                '<a href="#/tab/badgeboard" class="item" ng-repeat="item in id_list | filter:inputSearch" ng-click="selectItem(item)">{{item.employeeName}}</a>' +
             '</div>' +
         '</ion-content>' +
     '</ion-popover-view>';
    return {
        restrict: 'A',
        scope: {
            params: '=ionicAutocomplete',
            inputSearch: '=ngModel'
        },
        link: function ($scope, $element, $attrs) {
            var popoverShown = false;
            var popover = null;
            $scope.id_list = $scope.params.id_list;
            //Add autocorrect="off" so the 'change' event is detected when user tap the keyboard
            $element.attr('autocorrect', 'off');

            popover = $ionicPopover.fromTemplate(popoverTemplate, {
                scope: $scope
            });
            $element.on('focus', function (e) {
                if (!popoverShown) {
                    popover.show(e);
                }
            });
            $scope.selectItem = function (item) {
                $element.val(item.display);
                popover.hide();
                $scope.params.onSelect(item);
            };
        }
    };
}

);

{{item.employeeName}}不会在弹出窗口中打印任何内容,因为"id_list"为空(这是不正确的)。

如果我把以下代码

$scope.id_list = [
    {employeeName: 'Hello'},
     ];

在 .then() 之外,一切正常{{item.employeeName}}在弹出窗口中打印员工姓名

这是 html(视图)中的代码,它是一个输入字段并显示弹出式

        <input type="text" ionic-autocomplete="{id_list: id_list, onSelect:onSelect}"placeholder="Search ?" ng-model="search">

我尝试了$rootScope但失败了。我做错了什么?我该如何解决这个问题?

一点理论:

$http.get回报的称为承诺。它被异步解析(成功时)或被拒绝(出现问题时)。如果你参考角度承诺文档,then()接受 2 个函数,一个用于解析,一个用于拒绝。

通常$http调用应该在角度服务("服务"或"工厂",这两者非常相似)中进行。这样的服务可以注入到任何控制器或指令中并重用。

在您的情况下:

你的承诺很有可能被拒绝,因此执行的是你传递给then()的第二个函数,它目前是空的。

先检查一下这个,然后让我知道。

代码中访问 $scope.id_list 的另一种方法,你可以试试这个

var id_list=[];
 $http.get(config.url+'/api/employees-suggestion/??token=' + currentUser.token + '&filterEmployee='+ "10000191")
.then(function(response) {
    console.log(response);
       id_list = {employeeName: 'Hello'};
      id_list.push({id_list: id_list});
      console.log("id_list="+id_list);
   }, function(response) {
       }
 )

在这里$scope.id_list.push({id_list: id_list});将帮助您在UI中显示。

 <input type="text" ionic-autocomplete="{id_list: id_list, onSelect:onSelect}"placeholder="Search ?" ng-model="search">

和您的选择。

$scope.onSelect = function (item) {
        console.log('item', item);
    };

这应该可以正常工作

添加$scope.$apply() 在回调中设置结果后,它将允许 angular 查看超出其正常行为的更改

用你的$http.get做一个服务

angular.module('MyApp')
  .service('yourService',['$http', function ($http) {
    this.doMyGet = function ( callbackFunc ) {
      $http.get('YOURURL')
        .success(function (response) {
            callbackFunc(response);
        })
        .error(function (response) {
            console.log('error');
        });
    };
}]);

将服务作为参数传递给控制器以使用它,如下所示:

yourService.doMyGet( function (response) {
    $scope.getMyResponse = response;
});