【问题标题】:Angular generated project, unresponsive controller [duplicate]Angular生成的项目,无响应的控制器[重复]
【发布时间】:2020-02-07 15:33:51
【问题描述】:

对于这个宽泛的问题,我很抱歉,但我很难指出我的问题。 我使用“ng new”命令生成一个新的角度项目,但是当我尝试在项目中使用控制器时,它们仍然没有响应。 为确保它不是我的代码,它从以下位置获取了一个代码块:https://www.w3schools.com/angular/angular_events.asp(ng-click 指令示例 2)也可以在下面看到:

在单个 index.html 文件中运行此代码时,角度控制器是响应式的,并且当点击时,我的屏幕上的计数会发生变化。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <button ng-click="myFunction()">Click me!</button>
        <p>{{ count }}</p>
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.count = 0;
            $scope.myFunction = function () {
                $scope.count++;
            }
        });
    </script>
</body>
</html>

但是在我的应用程序中插入代码时,格式基本相同,但没有“DOCTYPE”、“html”和“script src=...”标签(如下所示),应用程序变得无响应。

<div ng-app="myApp" ng-controller="myCtrl">

    <button ng-click="myFunction()">Click me!</button>
    <p>COUNT:</p>
    <p>{{ count }}</p> 
</div>
<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope) {
        $scope.count = 0;
        $scope.myFunction = function () {
            $scope.count++;
        }
    });
</script>

我不确定还有哪些其他文件可以解决这个问题,但请写下来,我会提供它们,但目前我没有制作其他控制器,并且上述 .html 文件位于app.component.html

【问题讨论】:

    标签: angularjs angular angularjs-controller


    【解决方案1】:

    第一件事是当前的角度不支持ng-click并且都不要参考w3schools这是一个过时的教程,我建议你去https://angular.io/(角度的官方文档)

    解决你的问题 angular 2+ 有不同的语法,没有控制器,所以它不起作用

    你的 app.component.html 应该是:

    <div>
        <button (click)="myFunction()">Click me!</button>
        <p>{{ count }}</p>
    </div>
    

    你的 app.component.ts

    export class AppComponent {
    
        public count    :    number    =    0;
    
        constructor() {}
    
        public myFunction() {
            this.count  =    this.count + 1;
        }
    }
    

    【讨论】:

      【解决方案2】:

      ng new 命令不会生成 angularjs 应用。它生成 Angular App,这是非常不同的:

      • Angular 是用 Typescript 编写的(大部分时间),就像 Angular 是用 Javascript 编写的(大部分时间)
      • Angular 正在积极开发中(撰写本文时为第 9 版),Angularjs 的长期支持将持续到 2021 年 6 月 30 日。
      • Angular 使用了大部分新的浏览器功能,因为 AngularJs 遇到了旧的兼容性问题。
      • 还有更多,check out this link

      在您的情况下,您正在学习 angularjs 教程。这不适用于您的上下文。

      你仍然可以使用 angularjs,但建议迁移到 Angular。如果您仍然希望创建一个 angularJS 应用程序,您可以毫无问题地按照该教程进行操作。但是,您无法使用ng new 创建新应用。

      但是,如果您正在寻找 Angular 教程,我建议您查看他们的 Hero tutorial,它制作精良且易于理解。

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 1970-01-01
        • 2014-07-28
        • 1970-01-01
        • 2019-04-20
        • 2015-12-06
        • 1970-01-01
        • 1970-01-01
        • 2016-01-02
        相关资源
        最近更新 更多