Angular.js:如何在模块中创建控制器?

时间:2013-04-01 03:45:57

标签: module angularjs controls

我想在使用模块时定义一个控制器:

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

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

})

然后我想使用模块和ccontroller:

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

但它没有渲染,我的代码出了什么问题?

5 个答案:

答案 0 :(得分:15)

您的控制器错误,无需返回功能。

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

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

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

演示:Plunker

答案 1 :(得分:2)

官方文件:

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

语法:

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

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

没有太大的不同,但这个也有效。

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

答案 4 :(得分:0)

使用JS严格模式也可以这样做 -

(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"):

   }

])

})();