2015-10-19 35 views
1

我是中的新成员。我想要做的是在角度应用程序中添加一个简单的控制器。所以,我的代码是像这个 -Angular.JS - 添加控制器时出错

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
    </head> 
    <body> 
     <div ng-app=""> 
      <div ng-init="mySwitch=true"> 
       <p> 
       <button ng-disabled="mySwitch">Click Me!</button> 
       </p> 
       <p> 
       <input type="checkbox" ng-model="mySwitch"/>Button Disable 
       </p> 
       <p> 
       {{ mySwitch }} 
       </p> 
      </div> 
     </div> 
    </body> 
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
</html> 

所以,它是工作perfectly-

enter image description here

当我ADDD ng-controller="anything"这样...

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
    </head> 
    <body> 
     <div ng-app=""> 
      <div ng-controller="anything" ng-init="mySwitch=true"> 
       <p> 
       <button ng-disabled="mySwitch">Click Me!</button> 
       </p> 
       <p> 
       <input type="checkbox" ng-model="mySwitch"/>Button Disable 
       </p> 
       <p> 
       {{ mySwitch }} 
       </p> 
      </div> 
     </div> 
    </body> 
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
</html> 

似乎没有任何工作。

enter image description here

任何人都可以请大家帮忙,我在做什么错?

在此先感谢您的帮助。

+0

看起来像你需要你为什么'ngRoute'在这个依赖定义控制器 – scniro

回答

1

看起来像你还没有定义一个控制器。遵守以下...

<div ng-app="app"> 
    <div ng-controller="ctrl"> 
[...] 

angular.module('app', []).controller('ctrl', function($scope) { 
    $scope.mySwitch = true; 
}); 

JSFiddle Link - 工作演示

和往常一样,请参阅Understanding Controllers文档的更多信息。

1
在您需要以后你的应用程序定义一个名字

用于为例

Module.js

var home = angular.module("home",['ngRoute']); 

调用此变种在你的控制器

控制器的第一步

.js

home.controller('homeController',function($scope){ 
    $scope.switch = value; 
}); 

在你的代码的HTML

的index.html

<!DOCTYPE html> 
<html ng-app="home"> 

<div ng-controller="homeController" > 
{{switch}} 
</div> 
+0

?另外,你的答案与我之前发布的答案有什么不同? – scniro

+0

只有我的朋友的新信息,如果你分开文件夹中的代码,它使得易于管理 –