Reputation: 15
I am trying to use a controller that I wrote and saved in a controller.js file, but it won't work in my html code. I have the code written as: (This is the version that doesn't work correctly)
<div ng-app="myApp" ng-controller="movieCtrl">
..bit of my html code..
</div>
<script src="controller.js"></script>
This version however works just fine:
<div ng-app"myApp" ng-controller="movieCtrl">
irrelavent html code here
</div>
<script>
var app = angular.module('myApp', []);
app.controller('movieCtrl', function($scope, $http) {
$scope.$watch('search', function() {
fetch();
});
$scope.search = "tt2975590";
function fetch() {
$http.get("http:www.omdbapi.com/?i=" + $scope.search + "&plot=full&r=json")
.then(function(response) {
$scope.details = response.data;
});
}
$scope.update = function(movie) {
$scope.search = movie.Title;
}
});
</script>
How do I get it to work with the controller in its own controller.js file?
Upvotes: 0
Views: 1488
Reputation: 116
So, as discussed, the problem was the relative path. Solution: Change the src attribute to "../app/controllers/controller.js".
Upvotes: 0
Reputation: 1810
You didn't instantiate your controller properly in your HTML code.
Here is a much cleaner solution that works. Remember to change ng=controller
to ng-controller
in your html code.
HTML Markup
<div ng-app="myApp" ng-controller="movieCtrl">
//bit of html and Angular code such as...
<input type="text" ng-model="watchInput" Placeholder="Type Something"/>
<p>{{watchInput}}</p>
</div>
<script src="controller.js"></script>
Controller in controller.js
Your AngularJS Controller should look something like...
myApp = angular.module ("myApp", []);
myApp.controller("movieCtrl", ["$scope", function($scope){
//Your Controller code goes here
}]);
Hope this helps. Please let me know.
Upvotes: 0
Reputation: 2561
It isn't working because you have a syntax error here ng=controller="movieCtrl"
.
It should be ng-controller="movieCtrl"
I am assuming the rest of your code is correct. If that is right, then this change should fix your problems.
Upvotes: 1