Angular ng-model and controller won't work

304 Views Asked by At

I'm fairly new to Angular and I am trying to use ng-model and ng-controller to change some text using an input box.

This issue is that my initial text(john) doesn't show up on the page. Every tutorial says this is the way to do it. Am I missing some import or declaration somewhere in the component.ts?

Here is my code.

var app = angular.module('myApp', [])
app.controller('myCtrl', function($scope){
    $scope.firstName = "john";
});
<div ng-app="myApp" ng-controller="myCtrl">

    <h1>{{firstName}}</h1>
    Name: <input ng-model="firstName">
    
</div>

4

There are 4 best solutions below

0
Joshua Poling On

I don't see where you're including angular though. Add it into your code.

Example:

        <!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">
    
        <h1>{{firstName}}</h1>
        Name: <input ng-model="firstName">
        
    </div>
    
    <script>
        var app = angular.module('myApp', [])
        app.controller('myCtrl', function($scope){
            $scope.firstName = "johns";
        });
    </script>
    </body>
    </html>

0
Ihor Yanovchyk On

You forgot to inject $scope into your controller.

myApp.controller('myCtrl', ['$scope', function($scope) {
  $scope.firstName = 'john';
}]);

Any dependency (services, filters..) you want to have in the controller you must inject.

0
georgeawg On

Add the angular.js library as a <script> element:

var app = angular.module('myApp', [])
app.controller('myCtrl', function($scope){
    $scope.firstName = "john";
});
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

    <h1>{{firstName}}</h1>
    Name: <input ng-model="firstName">
    
</div>

0
Saghi Shiri On

You didn't miss any declaration, but the problem might be because you did not include angular and your code inside html. Try this:

    <html>
    <head></head>
    <body ng-app="myApp">

    <div ng-controller="myCtrl">
        <h1>{{firstName}}</h1>
        Name: <input ng-model="firstName">
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
    <script src="./component.ts"></script> <!--your component file location-->
    </body>
    </html>