hh54188
hh54188

Reputation: 15656

Angular.js: How to create controller in module?

I want define a controller when use module:

angular.module('todoList', [], function () {

}).controller('myCtrl', function ($scope) {
    return function ($scope) {
        $scope.todos = [
            {
                text: "Hello"
            }, {
                text: "World"
            }
        ]
    }

})

then I want use the module and the ccontroller:

<div ng-controller="myCtrl" ng-app="todoList">  
        <li ng-repeat="todo in todos">
            <span>{{todo.text}}</span>
        </li>>
</div>

but it render nothing, what's wrong with my code?

Upvotes: 12

Views: 34051

Answers (5)

dprobhat
dprobhat

Reputation: 152

You can do like this too by using JS strict mode-

(function() {
'use strict';
angular.module('listProject', []);
})();

(function() {
'use strict';
angular.module('listProject').controller('MyController', ['$scope', 
  function($scope) {
    console.log("Hello From ListProject Module->My Controller"):

   }

])

})();

Upvotes: 0

Bijan
Bijan

Reputation: 26517

Official Docs:

http://docs.angularjs.org/guide/controller

Syntax:

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

myApp.controller('GreetingController', ['$scope', function($scope) {
  $scope.greeting = 'Hola!';
}]);

Upvotes: 2

Rajnish Bakaria
Rajnish Bakaria

Reputation: 116

var myName1=angular.module("myName",[]);
myName1.controller("nameInfo",["$scope",function($scope){
$scope.name="Rajnish";
$scope.address="Delhi";
}
])

Upvotes: 1

Otpidus
Otpidus

Reputation: 519

Not much different but this one works too.

angular.module('todoList', []).
    controller('myCtrl', 
      function ($scope){
       $scope.todos=[{text: "Hello"},{text: "World"}];
     });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

Your controller is wrong, there is no need to have a return function.

angular.module('todoList', [], function () {

}).controller('myCtrl', function ($scope) {

        $scope.todos = [
            {
                text: "Hello"
            }, {
                text: "World"
            }
        ]
})

Demo: Plunker

Upvotes: 15

Related Questions