0

How to pass scope data to simple array? I tried to change function to change $scope.categoryname to arr array.

$scope.categoryname = [];

$scope.getCategory = function() {
    $http({
        url: 'http://127.0.0.1:8081/category/name',
        method: "GET",
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "application/json"
        }
    })
    .then(function (response) {
            console.log("SUCCESS");
            console.log(response);
            $scope.categoryname = response.data;
            },
        function (response) { // optional
            console.log("ERROR");
            console.log(response);
     });
};

$scope.getCategory();
var arr = $scope.categoryname;
var res = '';
for (var i = 0; i < arr.length; i++) {
    res += '<a ng-click="getProductsByCategory(' + (i + 1) + ')" ng-model="category.id">' + arr[i] + '</a>';
}
var wrap = document.getElementsByClassName('ffffffff')[0];
wrap.innerHTML = res;
Ayan
  • 1
  • 2
  • Did you try async/await ? – Ashish Oct 28 '20 at 07:27
  • 1
    `getCategory` is async, so `categoryname` is not set just after function call. Await function, or execute your code after assignment in `then` clause – Ivan Ivanov Oct 28 '20 at 07:29
  • async/await how to use it? never used before – Ayan Oct 28 '20 at 07:31
  • `"Access-Control-Allow-Origin": "*",` — This is a response header, is has no place being on a request. – Quentin Oct 28 '20 at 07:56
  • `"Content-Type": "application/json"` — You are making a GET request, you aren't POSTing JSON (or PUTting JSON). There's no request body to describe the type of. That header is nonsense in this context. – Quentin Oct 28 '20 at 07:56
  • It *looks* like you are trying to use Angular, and I'd be surprised if it didn't have its own patterns for using Ajax and if adding content via `innerHTML` didn't work very well. You should probably look for an Angular-specific Ajax tutorial. – Quentin Oct 28 '20 at 07:59
  • @Quentin yeah it works the same even without header – Ayan Oct 28 '20 at 08:10

1 Answers1

-2

 $scope.getCategory = function() {
        $http({
            url: 'http://127.0.0.1:8081/category/name',
            method: "GET",
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Content-Type": "application/json"
            }
        })
            .then(function (response) {
                    console.log("SUCCESS");
                    console.log(response);
                    $scope.categoryName = response.data;
                    arr = $scope.categoryName;
                    },
                function (response) { // optional
                    console.log("ERROR");
                    console.log(response);
                });
    };
    $scope.getCategory();



    var arr = [];
York Chen
  • 744
  • 4
  • 9
  • didnt work when I make response there is data when I response arr array there is [] – Ayan Oct 28 '20 at 07:45