AngularJS报错:Argument with 'controller' is not a function, got undefined 求解决
Hey there! I totally get how frustrating it is to hunt for solutions to a problem and come up empty-handed—let’s walk through getting your AngularJS app to pull and show database data correctly. First, let’s start with the code snippet you shared, then fill in the missing pieces that are likely causing the issue.
Your Index.php Snippet
<header> <script type='text/javascript' src='local-path/js/angular.min.js?ver=4.9.5'></script> <script type='text/javascript' src='local-path/js/angular-route.min.js?ver=4.9.5'></script> <script type='text/javascript' src='local-path/js/scripts.js?ver=4.9.5'></script> <!-- Rest of your header content --> </header>
Step 1: Set Up Your AngularJS Module & Route
First, make sure your AngularJS module is properly initialized in scripts.js—since you’re using angular-route, this is critical for routing and linking your controller to the view:
// scripts.js var app = angular.module('myApp', ['ngRoute']); // Configure routes to map your view and controller app.config(function($routeProvider) { $routeProvider .when('/data', { templateUrl: 'views/data-view.html', // Your HTML view file controller: 'DataController' // Controller that handles data fetching }) .otherwise({ redirectTo: '/' }); });
Step 2: Create a Backend PHP API to Fetch Database Data
You need a PHP endpoint that connects to your database and returns data in JSON format (AngularJS works seamlessly with JSON). Let’s name this fetch-data.php:
<?php // fetch-data.php header("Content-Type: application/json"); // Database connection (update credentials to match your setup) $servername = "localhost"; $username = "your_db_username"; $password = "your_db_password"; $dbname = "your_db_name"; $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die(json_encode(["error" => "Connection failed: " . $conn->connect_error])); } // Query to retrieve data (adjust table/columns as needed) $sql = "SELECT id, name, email FROM your_table_name"; $result = $conn->query($sql); $data = []; if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $data[] = $row; } } echo json_encode($data); $conn->close(); ?>
Step 3: Build the AngularJS Controller to Fetch Data
Add this controller to scripts.js—it uses AngularJS’s $http service to call your PHP API and store the data in the scope:
// Add this to scripts.js app.controller('DataController', function($scope, $http) { // Initialize empty array to hold data $scope.dataList = []; // Fetch data from the PHP endpoint $http.get('fetch-data.php') .then(function(response) { // On success, assign data to scope for view binding $scope.dataList = response.data; }, function(error) { // Handle errors (log to console or show to user) console.error('Error fetching data:', error); $scope.errorMessage = 'Failed to load data. Please try again later.'; }); });
Step 4: Create the View to Display Data
Make the data-view.html file (referenced in your route) to bind the fetched data using AngularJS’s templating:
<!-- views/data-view.html --> <div ng-controller="DataController"> <!-- Show error message if fetch fails --> <div ng-if="errorMessage" class="alert alert-danger">{{ errorMessage }}</div> <!-- Display data in a table --> <table class="table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <tr ng-repeat="item in dataList"> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td>{{ item.email }}</td> </tr> </tbody> </table> </div>
Step 5: Common Issues to Troubleshoot
- File Paths: Double-check that paths to your AngularJS scripts,
fetch-data.php, and view files are correct (relative toindex.php). - Database Credentials: Ensure
fetch-data.phpuses the right username, password, and table names for your database. - Console Errors: Open your browser’s developer tools (F12) and check the Console tab for JavaScript errors—this is often the fastest way to spot issues.
- Version Compatibility: Confirm that
angular-route.min.jsis compatible with yourangular.min.jsversion (4.9.5). - Server/CORS Issues: If your frontend and backend are on different ports/domains, you might hit CORS errors—host them on the same server or add CORS headers to your PHP endpoint.
If you’re still stuck, share more details like your full scripts.js code, console error messages, or database table structure, and we can dig deeper.
内容的提问来源于stack exchange,提问作者Ashish Patel

