0

Here is my controller code

 $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) {
       }
 )

i want to get the value of '$scope.id_list' and use it in another an external js file(which is a custom directive for ionic-autocomplete). Here is directive code,

    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}} doesn't print anything in the pop-over as 'id_list' is empty (which is not correct).

if I put following code

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

outside of .then() everything works correctly {{item.employeeName}} prints the employeeName in the pop-over

This is the code in html (view) which is an input field and shows drop-pop-over

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

I tried $rootScope but failed. What am I doing wrong? How can i solve this?

10
  • Is your console.log inside then(function(response) getting printed ? Apr 21, 2016 at 11:01
  • the second callback function of http.get is for error, have you checked console.log in that function Apr 21, 2016 at 11:02
  • Yes it does @NikhileshKV Apr 21, 2016 at 11:04
  • try this. define $scope.id_list = [] before your get request and check. Apr 21, 2016 at 11:08
  • @NikhileshKV i re-checked but i already did that initialization of id_list=[]. Apr 21, 2016 at 11:16

4 Answers 4

2

A bit of theory:

What $http.get returns is called a promise. It is asynchronously resolved (when successful) or rejected (when something goes wrong). If you refer to angular promises documentation, then() accepts 2 functions, one for resolve and one for reject.

Usually $http calls should take place inside angular services (a "service" or a "factory", these two are very similar). A service like that can be injected into any controller or directive and be reused.

In your case:

There is a good chance that your promise gets rejected, hence what gets executed is the second function you pass to then(), and it's currently empty.

Check this one first, and let me know.

0

An alternate way of accessing $scope.id_list in you code you can try this

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) {
       }
 )

here $scope.id_list.push({id_list: id_list}); will help you to display in UI.

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

and your onSelect

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

    };

this should work fine

0
0

Add $scope.$apply() after you set your result in the callback it will allow angular to see changes made outside of his normal behavior

1
  • 1
    Callbacks from promises (such as returned by $http) are already handled within the angular digest loop. Don't throw random $apply() calls into the code where they aren't needed.
    – Duncan
    Apr 21, 2016 at 11:16
0

Make a service with your $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');
        });
    };
}]);

Pass the service as a parameter to your controller to use it as shown here:

yourService.doMyGet( function (response) {
    $scope.getMyResponse = response;
});
2
  • Should i pass it to the directive also? Apr 21, 2016 at 11:58
  • It depends. If you want to use the services within the directive, then yes. Otherwise it is not necessary
    – Mast
    Apr 21, 2016 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.