angularjsangularangularjs-controller

Angular generated project, unresponsive controller


I'm sorry for the broad question but I'm having a hard time pin pointing my problem. I use the "ng new" command to generate a new angular project, but when i try to utilize controller in the project they remain unresponsive. To assure it was not my code it took a code block from: https://www.w3schools.com/angular/angular_events.asp (The ng-click Directive example 2) can also be seen below:

when running this code in a single index.html file the angular controller is responsive and the count changes on my screen, when clicked.

<!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>

but when inserting the code in my application, formatted basically the same but without the "DOCTYPE", "html" & "script src=..." tags (can be seen below) the application becomes unresponsive.

<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>

I'm not sure what other files can be of interest to solving this problem but please write and i will provide them, but currently i have made no other controllers, and the above mentioned .html file is in a sub component of the app.component.html


Solution

  • The first thing is the current angular won't support the ng-click and all don't refer the w3schools it's an outdated tutorial, I would suggest you go with the https://angular.io/ (angular's official documentation)

    Coming to your problem angular 2+ has a different syntax no controllers so it won't work

    Your app.component.html should be:

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

    Your app.component.ts

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