我的angular应用程序不起作用
my angular app does not work
我有这个代码:
<!doctype html>
<html ng-app="myApp" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function ($scope) {
$scope.count = 0;
$scope.increment = function (){
$scope.count = $scope.count + 1;
}
});
</script >
<div ng-controller="FirstCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
它怎么了?当我在没有控制器的情况下工作时,它可以正常工作,但当我使用应用程序和app.controller时,它不会工作。为什么?我做错什么了吗?
"Controller as"语法仅在1.1.5+版本中可用
据我所知,当使用"Controller as"时,如果你想引用一个具有指定控制器别名的变量(在你的情况下是"app1"),那么你应该在控制器中使用"this."语法对变量进行分类,或者访问不带"app1"的变量,然后它会尝试从作用域中获取它。
http://jsbin.com/zehagogoku/3/edit
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function ($scope) {
this.count = 0;
this.increment = function (){
this.count = this.count + 1;
};
$scope.count = 0;
$scope.increment = function(){
$scope.count = $scope.count + 1;
};
});
您在这里混合样式。在HTML中,您使用Controller As语法,在其中编写FirstCtrl as app1
。这在作用域上生成一个名为app1
的对象,该对象是FirstCtrl
的实例。app1.count
、app1.increment()
等将是FirstCtrl
对象的属性。
在控制器中,您没有在控制器上创建属性。相反,您将变量指定为$scope
对象的属性。
使用$scope
的优势在于,它本质上是一个全局对象,因此可以从应用程序中的任何位置访问它。然而,它的缺点也源于它是一个全局对象。
您可以更改javascript以匹配Controller As语法,如图所示:
app.controller("FirstCtrl",function () {
//create an alias to this for consistent reference
var app1 = this;
app1.count = 0;
app1.increment = function (){
app1.count += 1;
};
});
或者,您可以将HTML更改为使用$scope
:
<div ng-controller="FirstCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
javascript中的更改:
$scope.count += 1;
注意,您不必在HTML中引用$scope
,因为它的存在是隐含的。然而,javascript $scope.count = this.count + 1;
中的这一行在任何一种情况下都不会起作用,再次是因为您在混合样式。
此外,如前所述,Controller as语法需要Angular 1.1.5或更高版本。
- 在phonegap应用程序内部重定向不起作用
- 鼠标事件在OpenLaszlo应用程序中不起作用
- JavaScript onScroll在谷歌应用程序脚本web应用程序中不起作用
- getRange(单元格)在谷歌应用程序脚本中不起作用
- javascript_include_tag'应用程序'不起作用
- 如果应用程序托管在IIS上,则Javascript window.location.htm不起作用
- Angular.js ajax和应用程序不起作用
- window.open()在使用phone gap的iOS应用程序上不起作用
- if-else循环和jquery在热应用程序或冷应用程序中不起作用
- 多语言应用程序中的Angular JS路由不起作用
- Node.js应用程序中的编辑不起作用
- Slick Carousel在应用程序动态路由的基础上不起作用
- 我的angular应用程序不起作用
- coffee脚本没有'在我的ruby应用程序中不起作用
- 为什么chrome.sockets.tcp.create()在应用程序后台脚本中不起作用
- 比较应用程序脚本中的两个数组不起作用
- 引导图示符在java Web应用程序中不起作用
- 为什么我的CSS在我的Rails应用程序上不起作用
- 选项卡在 MVC 应用程序中不起作用
- ng-change在AngularJS应用程序中不起作用