sukesh
sukesh

Reputation: 2425

AngularJs - Use External controller.js

Just started with Angular and trying to make this work.

I would like to display the name in the <p></p>, but it shows {{ name }}.

ASPX:

<html ng-app="myApp">
<head runat="server">
    <script src="Assets/Vendor/angularjs-v1.2.28.js"></script> 
    <script src="App/app.js"></script>  
    <script src="App/controllers.js"></script>

</head>
<body ng-controller="myCtrl">
<p>{{ name }}</p>
</body>
</html>

app.js:

var app = angular.module('myApp','myCtrl');

controllers.js:

var controller = {};

controller.myCtrl = function ($scope) {
    $scope.name = "abcd";
}

EDIT: I have changed the order of loading the script files and updated this query. This is the error I see in console - Uncaught Error: [$injector:modulerr]

Upvotes: 2

Views: 2526

Answers (2)

Davin Tryon
Davin Tryon

Reputation: 67306

Few things here:

1 - myCtrl is not a dependent module. So, you don't need it when defining the myApp module:

angular.module('myApp',[]);

2 - Order of scripts, as described by @Highmastdon.

3 - When defining the controller, you can use the myApp module:

angular.module('myApp').controller('myCtrl', function($scope) {

    $scope.name = 'abcd';
});

Upvotes: 3

Highmastdon
Highmastdon

Reputation: 7520

You've not correctly put the order of the scripts. Rather put app.js in front of controller.js. Now you're getting the error: var app is not defined.

[Addition]
Furthermore, you're trying to inject myCtrl which is no object. So changing var controller to var myCtrl would probably work.

Better would be to use something as described here: https://docs.angularjs.org/guide/controller

app.controller('myCtrl', ['$scope', function($scope) {
  $scope.name = "abcd";
}]);

Upvotes: 4

Related Questions