Search code examples
phpangularjscrudangularjs-ng-click

Angular JS / PHP- can read data from database but ng-click not working


Now I can read the PictureName from database and show it on the browser. (Picture below: black block on the left) Picture

And what I want to do is that, when do click on one of rows (ex: pic1), it will trigger function change().

But no matter what I try, function change() doesn't work. What should I do to my code? Thanks for the answers and suggestions. :)

read.php

<?php    
require 'lib.php';    
$object = new CRUD();

// table header
$data = '<table style="border-collapse:separate; border-spacing:0px 10px;">
            <tr>
                <th>No. </th>           
                <th>PictureName</th>
            </tr>';

// table body

$picturetb = $object->Read();

if (count($picturetb) > 0) {
    foreach ($picturetb as $key=>$picture) {
        $data .= '<tr ng-click="change()">
                <td>' . $key . '</td>
                <td><a>' . $picture['Picture_Name'] . '</a></td>            
            </tr>';
    }
}

$data .= '</table>';
echo $data;
?>

angular.js

var mainApp = angular.module("mainApp", []);
mainApp.controller('MyController', function ($scope) {

    $scope.readRecords = function () {
        $.get("ajax/read.php", {}, function (data, status) {            
            $(".addPicture").html(data);
        });
    }

    $scope.change = function () {
        console.log("do click");
    }
}

Solution

  • Well you could use $compile but generally it is a very, very bad idea to inject markup this way. Why not return the key / picture as JSON:

    $arr = [];
    foreach ($picturetb as $key=>$picture) {
      $arr[] = array('key' => $key, 'picture' => $picture['Picture_Name']);
    }
    echo json_encode($arr);
    

    Retrieve it like this

    $scope.readRecords = function () {
      $.get("ajax/read.php", {}, function (data, status) {            
        $scope.data = data;
      });
    }
    

    In your view:

    <table style="border-collapse:separate; border-spacing:0px 10px;">
      <thead>
        <tr>
          <th>No. </th>           
          <th>PictureName</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-click="change()" ng-repeat="d in data">
          <td> {{ d.key }} </td>
          <td><a> {{ d.picture }} </a></td>
        </tr>
      </tbody>
    </table>