0

I'm new to AngularJS and I'm trying to figure out why some of the documentation code isn't working for me. While the global function controller below works for me, the documentation says I should be creating the controller through the Angular module.

Here is a link to a JSFiddle with the same code.

Working JS Controller:

function MyController($scope) {
  $scope.username = 'World';

  $scope.sayHello = function() {
    $scope.greeting = 'Hello ' + $scope.username + '!';
  };
}

Broken JS Controller:

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

myApp.controller('MyController', ['$scope', function($scope) {
  $scope.sayHello = function() {
    $scope.greeting = "Hi " + $scope.username;
  };
}]);

HTML File:

<div ng-app="">
  <div ng-controller = "MyController">
    Your name:
      <input type="text" ng-model="username">
      <button ng-click='sayHello()'>greet</button>
    <hr>
    {{greeting}}
  </div>
</div>

1 Answer 1

1
<div ng-app="myApp">

You have to specify the name of the app you are using, since the controller belongs to that module.

updated version of your js: http://jsfiddle.net/PH5yK/2/

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I knew it had to be that simple. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.