繁体   English   中英

我的角度应用程序不起作用

[英]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和app.controller时却无法正常工作。 这是为什么? 难道我做错了什么?

您在这里混合样式。 在HTML中,您使用Controller As语法,其中FirstCtrl as app1FirstCtrl as app1 这将在作用域上创建一个名为app1的对象,该对象是FirstCtrl的实例。 app1.countapp1.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;这一行$scope.count = this.count + 1; 在任何情况下都将永远无法工作,再次是因为您正在混合样式。

另外,如前所述,Controller As语法需要Angular 1.1.5或更高版本。

“ 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;
  };

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM