0

I'm new to Angular JS. Here i have some doubt. I have this code:

.controller("boardController", function($scope, $http) {

   $scope.models = {
        selected: null,
        lists: {"A": [], "B": []} 
    };

    $http({ 
        method  : "get",
        url     : "/boards"
    })
    .then(function(response){
      $scope.ajax_val = response.data;
      angular.forEach($scope.ajax_val, function(value, key){
      var bname = value.board_name;
       $scope.models.lists.push(bname);
    });
  });

In this code push function returns error.. I dont know why?

Thanks Advanced!!...

6
  • $scope.models.lists is not an array. You can't use push method on it. You can use $scope.models.lists.A.push() or $scope.models.lists.B.push() Commented Nov 1, 2016 at 11:25
  • here i want to add dynamic names from database in lists array. and each names have one array. Commented Nov 1, 2016 at 11:26
  • Thanks Natiq... But i want to add A, B as dynamically. and add C, D, E etc. Commented Nov 1, 2016 at 11:28
  • What is response.data format? Can you give example data? Commented Nov 1, 2016 at 11:28
  • This is the response from laravel. [{"board_name":"boardone","id":1},{"board_name":"boardtwo","id":2}] Here i want to add these board one, board two as A, B, C.... Commented Nov 1, 2016 at 11:31

1 Answer 1

1

This is a JavaScript question, not about AngularJs itself.

But, you are getting this error because "lists" is an object and not an array, so it does not have the push function.

See more at: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object

I suggest you to change your approach to something like:

.controller("boardController", function($scope, $http) {

$scope.models = {
    selected: null,
    lists: [] 
};

$http({ 
    method  : "get",
    url     : "/boards"
})
.then(function(response){
  $scope.ajax_val = response.data;
  angular.forEach($scope.ajax_val, function(value, key){
    var bname = value.board_name;
    var model = {};
    model[bname] = [];
     $scope.models.lists.push(model);
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks.. K.. Then how to create a object dynamically using my response
I'm not getting what you want exactly, but I believe if you transform your "lists" in a properly array like: lists: [] and then push an object to it like: var myObj = {}; myObj[bname] = []; $scope.models.lists.push(myObj);
You're welcome SARAN, I'll update my answer to help others with the same doubt, could you please mark as answered if it has helped you?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.