angularjs - What is the correct way to add a property of specific items from a different array to an object -


i have 2 different arrays, 1 holds categories whilst other holds pages.

categories array:

$scope.categories = [{   id: 1,   name: "test category" }]; 

pages array:

$scope.pages = [{   id: 1,   name: "test page",   category: 1 }]; 

i add associated pages category. can achieved knowing if category property page equal category's id.

at moment, wrote function loops through

function getpagesbyid(categoryid) {    var tmp = [];    (var = $scope.pages.length - 1; >= 0; i--) {     if($scope.pages[i].category == categoryid) {       tmp.push($scope.pages[i]);     }   };   return tmp;  }  function mergepages() {    var tmp = $scope.categories;    (var = tmp.length - 1; >= 0; i--) {      tmp[i].pages = getpagesbyid(tmp[i].id);    };    return tmp;  }  $scope.categories = mergepages(); 

is correct angular way achieve this?

there no right or wrong answer this. if interpret question 'can angular simplify this?' yes, can.

you can use angular filters condense mergepages function this:

function mergepages() {     angular.foreach($scope.categories, function (category)     {         category['pages'] = $filter('filter')($scope.pages, {category: category.id});     }); } 

this populate $scope.categories appropriate pages comparing category ids in filter.

here's fiddle demonstrates working.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -