我正在学习 AngularJs,我在互联网上完成了一些类(class),我知道什么是模块、 Controller 、服务,我知道一些基本指令,并且我在互联网上找到了一个基本的 AngularJs 视频教程,我正在这样做视频但不明白为什么它不起作用。 这是我的代码
var app = angular.module('todoApp', []);
app.controller('todoCtrl', ['$scope', function($scope) {
$scope.todos = [
{
text: "Learn AngularJs"
},
{
text: "Build App"
}
];
$scope.addTodo = function() {
$scope.todos.push({text: $scope.todoText});
};
}]);
<html ng-app="todoApp">
<head>
<title>todo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="/underscore-master/underscore-min.js"></script>
<script src="todo.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div ng-controller="todoCtrl">
<h2>Total todos: {{todos.length}}</h2>
<ul class="unstyled">
<li ng-repeat="todo in todos">
<span>{{todo.text}}</span>
</li>
</ul>
</div>
<form class="form-horizontal">
<input type="text" ng-model="todoText">
<button class="btn" ng-click="addTodo()"><i class="icon-plus">Add</i></button>
</form>
</body>
</html>
它应该在我的数组中插入新文本,但是当我单击按钮时没有任何反应,并且控制台中没有错误,我真的不明白为什么?
最佳答案
ng-click 事件超出了 Controller 的范围。快速的答案是将 ng-controller="todoCtrl"
移动到封闭/外部元素,在本例中为 body
。
关于javascript - Controller 函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30548007/