Search code examples
javascriptangularjsarraysangularjs-scopeangularjs-http

Data Array Always Process to String not Array With Angular.fromJson


I have a problem, I did set field form to array. Example : Field dfp_interest in response is []. So, i must set my data to array right ? I did and success in console.log. Result like --> ["5","6"] but when I process in angular.fromJson and i send with $http, my params dfp_interest is string not array. Am I wrong ? Give me solution or i do some mistakes ?

This is my process to send params in API

var a = angular.fromJson({
            "data" : "{\"username\": \"newshubid\", \"data\":{\"_id\": \""+ $scope.id +"\",\"label\": \""+ $scope.label +"\",\"active\": \""+ $scope.active +"\",\"parent_id\": \""+ $scope.parent_id +"\",\"level\": \""+ $scope.level +"\",\"meta_title\": \""+ $scope.meta_title +"\",\"meta_description\": \""+ $scope.meta_description +"\", \"meta_keyword\": \""+ $scope.meta_keyword +"\", \"dfp_interest\": \""+ $scope.tes +"\"}}"
        });

        var param = $.param(a);

        HttpService("POST", url, param, function(response){
            alert(response.message);
        });

This is example my data array for dfp_interest

$scope.tes = [5, 6];

$scope.testarray = $scope.tes.join("");

Solution

  • angular.fromJson accepts a string argument, with that said your code should be;

    var data = {username: 'newshubid', 
                data: { id: $scope.id, 
                        label: $scope.label, 
                        active: $scope.active,
                        parent_id: $scope.parent_id,
                        level: $scope.level,
                        meta_title: $scope.meta_title,
                        meta_description: $scope.meta_description,
                        meta_keyword: $scope.meta_keyword,
                        dfp_interest: $scope.tes }
               };
    
        var a = angular.fromJson(JSON.stringify(data));