2013-07-31 32 views
0

当我在$(function() {});方法中附上控制器代码时,它停止工作。请找到示例代码中提到bleow:

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': '[email protected]', 'phone': '123-2343-44' } 
      ]; 


     } 
    }); 
</script> 

如果我删除$(function() {});方法然后开始工作,提供所需的输出。 任何人都可以帮助我了解有关该问题的详细信息。

+2

为什么需要这个'$(函数( ){});'? – Cherniv

+0

$(function(){});一旦整个DOM准备就绪,我需要执行ContactController代码。 –

回答

2

通过将您的控制器与$(function() { });包装在一起,您正在创建一个闭合范围,因此ContactsController在该范围之外是不可见的,您的控制器应该具有根(窗)范围以便可访问!哟必须删除您的关闭或定义您的控制器为window.ContactsController = function(){}或简单地ContactsController = function(){}为了使它“公开”

+0

非常感谢您的详细解释。它帮助我了解问题的根源。 –

0

由于控制器在闭包中定义它是没有记录器可用于外部环境为了使此代码工作,你可以添加以下瓶盖内

$(function() { 

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

    myApp.controller('ContactsController', ['$scope', function($scope) { 
    // your code 
    }]); 

}); 

这样的代码不仅是模块化的,也是全球范围内/公共范围将不会被污染