I'm new to AngularJS and decided to try it out. As I read about it that I can simply plug into existing HTML and it will work. And now I'm stuck at this point.
Here is my shortened PHP code with wordpress and angularjs:
<?php
$the_query = new WP_Query(array('post_type' => 'products', 'nopaging' => 'true'));
<div class="container">
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<?php $name = get_field("name"); ?>
<?php $tree = get_field("tree"); ?>
<div class="material" ng-click="productMaterial(product)"
ng-init="product={name:'<?php echo $name; ?>',tree:'<?php echo $tree; ?>'};">
</div>
<?php endwhile; ?>
</div>
After the loop is done, then according to HTML source, all the ng-inits <div class="material">
-s get the correct values:
<div class="material" ng-click="productMaterial(product)" ng-init="product={name:'Castello',tree:'oak'};"></div>
..
<div class="material" ng-click="productMaterial(product)" ng-init="product={name:'Variostep CL',tree:'oak'};"></div>
My controller:
calculator.controller('Calc1ProductController', ['$scope', 'calc1Service', function($scope, calc1Service) {
$scope.productMaterial = function(product) {
console.log("Clicked product: " + $scope.product.name); // print always Variostep CL
};
}]);
So the problem is that every time I click on any product, always the last product gets printed in console that is Variostep CL
. I understand each new cycle in loop just overrides the previous product object and only the last product is stored.
How is it possible to pass the product data so, that whenever i click in webpage, the correct product data is logged to console?
As I have seen that other approach is to use pure angularjs approach, that I do the API request and receive JSON and then use instead of WP loop the ng-repeat, but then it will require me to rewrite even more code.
I was thinking to make an incrementing counter and store array of products and then access by the index in angular controller or maybe is there some simpler approach?
If my question is too messy, I can bring webpage snapshots and more clearer explanation. Thank you