简体   繁体   中英

Angular JS dynamic HTML from PHP ng-click not working

I am new in Angular JS,

I want to make a ng-click event in dynamically made HTML from PHP, here is the code.

var app = angular.module('pageapp',[]);

angular.module('pageapp')
.filter('to_trusted', ['$sce', function($sce){
    return function(text) {
        return $sce.trustAsHtml(text);
    };
}]);

app.controller('productList',function($scope,$http){
  $http.get("../webservice/api/get-products")
  .success(function(response){ 
    $scope.products = response.data; 
    $scope.paginationLinks = response.links;        
 });

 $scope.getPageData = function () {
    alert("Hello");
 }
});

HTML...

<section ng-controller="productList">
<table class="table table-responsive table-hover">
    <thead>
        <tr>
            <th>S.No</th>
            <th>Name</th>
            <th>Color</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="product in products">
            <td>{{$index + 1}}</td>
            <td>{{product.name}}</td>
            <td>{{product.color}}</td>
            <td>{{product.price}}</td>
        </tr>
    </tbody>
</table>
<ul class="pagination pull-right" ng-bind-html="paginationLinks|to_trusted""></ul>
</section>

PHP..

public function Products(){
    $start = 0;
    $perPage = 10;
    $count = DB::table('products')->count();
    $totalPages = ceil($count/$perPage);
    $data = DB::table('products')
            ->select('name','price','color')
            ->take($perPage)
            ->skip($start)
            ->get();

    for ($i=1; $i <= $totalPages; $i++) { 
        if($i == 1)
            $links ="<li><a href=''>".$i."</a></li>";
        else
            $links .="<li><a href='' ng-click='getPageData(".$i.")'>".$i."</a></li>";
    }

    return [
        'totalpages'    =>$totalPages,
        'data'          =>$data,
        'links'         =>$links
    ];
}

Instead of adding ng-click='getPageData(".$i.") in PHP, add ng-click="getPageData($event)" to your ul element in your HTML. Hence you can get the clicked li element (by event bubbling ) in your JS and you can do whatever you want.

hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM