To include a controller.js file into an ng-include HTML page, you can use the ng-controller directive in the ng-include tag. This will associate the specified controller with the content loaded by the ng-include. Here's how you can do it:

Assuming you have an HTML file named content.html that you want to include using ng-include, and the controller logic is defined in controller.js, follow these steps:

  1. controller.js: In your controller.js file, define your AngularJS controller. For example:

    // controller.js angular.module('myApp').controller('MyController', function($scope) { // Controller logic and scope variables go here $scope.message = "Hello from MyController!"; });
  2. HTML File: In your HTML file, make sure to include the controller.js file using a <script> tag before loading the content.html file through ng-include. Also, ensure you have included AngularJS itself.

    <!-- Include AngularJS --> <script src=""></script> <!-- Include your controller.js --> <script src="path/to/controller.js"></script> <!-- The main app module --> <div ng-app="myApp"> <!-- Include content.html using ng-include and specify the controller --> <ng-include src="'path/to/content.html'" ng-controller="MyController"></ng-include> </div>
  3. content.html: In your content.html file, you can use the controller's scope variables and functions as defined in controller.js. For example:

    <!-- content.html --> <div> <p>{{ message }}</p> <!-- Other content and bindings --> </div>

When the page loads, AngularJS will include content.html using ng-include, and it will also associate the MyController controller with the included content. As a result, any scope variables or functions defined in MyController will be accessible within the content.html file.

Make sure to replace path/to/controller.js and path/to/content.html with the actual paths to your files. Also, ensure that you have correctly defined the AngularJS module and app in controller.js and the main HTML file.

With these steps, you should be able to include a controller into an HTML page loaded through ng-include in AngularJS.

Have questions or queries?
Get in Touch