当我将控制器代码包含在$(function () {});
方法中时,它停止工作。请查看上面提到的示例代码:
Contacts.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Contacts</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="ContactsController">
<form>
<label>Name</label>
<input type="text" name="name" ng-model="newcontact.name" />
<label>Email</label>
<input type="text" name="email" ng-model="newcontact.email" />
<label>Phone</label>
<input type="text" name="phone" ng-model="newcontact.phone" />
<br />
<input type="hidden" ng-model="newcontact.id" />
<input type="button" value="Save" ng-click="saveContact()" class="btn btn-primary" />
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{contact.name}}</td>
<td>{{contact.email}}</td>
<td>{{contact.phone}}</td>
<td>
<a href="#" ng-click="edit(contact.id)">edit</a>
<a href="#" ng-click="delete(contact.id)">delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
<script type="text/javascript">
var uid = 1;
$(function () {
function ContactsController($scope) {
$scope.contacts = [
{ id: 0, 'name': 'Viral', 'email': 'hello@gmail.com', 'phone': '123-2343-44' }
];
}
});
</script>
如果我删除了$(function () {});
方法,那么它就会开始工作并提供所需的输出。
任何人都可以帮助我了解这个问题的细节。
答案 0 :(得分:2)
通过用$(function () { });
包装你的控制器你正在创建一个闭包范围,因此ContactsController
在该范围之外是不可见的,你的控制器应该有一个根(窗口)范围才能被访问!哟必须删除您的关闭或将您的控制器定义为window.ContactsController = function(){}
或简单地ContactsController = function(){}
才能使其“公开”
答案 1 :(得分:0)
由于控制器是在闭包中定义的,因此外部环境无法使用记录器以使此代码工作,您可以在闭包内添加以下内容
$(function () {
var myApp = angular.module('myApp',[]);
myApp.controller('ContactsController', ['$scope', function($scope) {
// your code
}]);
});
这样,代码不仅是模块化的,而且全局范围/公共范围也不会受到污染