Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I link an external javascript file to an AngularJS controller?

This may be a dumb question. I know AngularJS controllers use javascript code to keep the application logic outside of the view. But I was wondering if I could link an external javascript file to a controller so it didn't have to be so long.

If it is possible would you also share the syntax of how I would do this. Something like:

app.controller('demoCtrl', ['$scope', function ($scope) {
    $scope.msgtxt='Hello World';
    src=somejavascriptfile.js;
}]);
like image 941
Jared Whipple Avatar asked Feb 27 '15 23:02

Jared Whipple


People also ask

How do I connect an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How load JavaScript file in Angularjs?

To do load JavaScript files in a component, you have to do it manually inside the TypeScript file. Go into the app component TypeScript file and create a script element object. Then set the value of the src property to the path of the JavaScript file you want to load. This can be a URL or a local path in the project.

Can JavaScript be external?

External JavaScript is when the JavaScript Code(script) is written in another file having an extension . js and then we link this file inside the <head> or<body> tag of our HTML file in which the code is to be added.


1 Answers

If your issue is that the controller logic is too long, you are correct that it is a code smell. You want to make the controller as thin as possible, just enough logic to handle the view events and updating the model (scope). If you want to refactor your controller code, the first step is to extract out the logic into service(s) (in angular lingo providers / factories / services). The services can then be injected into your controller, similar to how you have injected the $scope service.

Read this sitepoint article for details on how to do this.

The next step might be look for logic (mainly UI related) which can extracted into directives.

In case you need to use an external javascript library within your angular application, the optimal way is to add that script to the scripts section of your html file, and wrap the functionality in a service or a directive (if it is UI related). Make sure to check if there are angular modules available out there for the 3rd party library you want to pull in.

like image 83
Scorpion-Prince Avatar answered Nov 13 '22 05:11

Scorpion-Prince