user1715408
user1715408

Reputation:

Data binding not working in my AngularJS app

I have the following html:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Basic</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js type="text/javascript">
        </script>
    </head>
    <body>
        <div ng-app="myApp">
            <input ng-model="to" type="email"
                placeholder="Recipient here.."/>
            <textarea ng-model="emailBody"
                placeholder="Email body here..">
            </textarea>
            <h2> {{ emailBody }} </h2>
        </div>
    </body>
</html>

I am referencing the emailBody data from the textArea but it doesn't bind the data associated. it just types {{ emailBody }} literally.

What am I doing wrong?

Upvotes: 1

Views: 278

Answers (2)

TGH
TGH

Reputation: 39248

Try adding the following to a java script file.

angular.module('myApp',[]).controller('myController',['$scope',function($scope){
  $scope.emailBody = 'test';
}]);

It defines the application/module and the emailBody field you are binding to.

You can then add a reference to the script bellow and also add a ng-contoller to reference the controller.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Basic</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js" type="text/javascript">
        </script>
        <script src='someUrlToYour JavaScript file'></script>
    </head>
    <body>
        <div ng-app="myApp" ng-controller='myController'>
            <input ng-model="to" type="email"
                placeholder="Recipient here.."/>
            <textarea ng-model="emailBody"
                placeholder="Email body here..">
            </textarea>
            <h2> {{ emailBody }} </h2>
        </div>
    </body>
</html>

Upvotes: 0

James
James

Reputation: 4681

Assuming you are playing with Angular for the first time, you might want to use the "ng-app" parameter without value, which will set an injection context without mapping it to a named application controller (which is missing in your example). Note also that you are missing a closing quote to the src parameter of your script tag.

Here is your example, with those two fixes, working just as expected.

<!DOCTYPE HTML>
<html ng-app>
    <head>
        <title>Basic</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js" type="text/javascript"></script>
    </head>
    <body>
        <div>
            <input ng-model="to" type="email" placeholder="Recipient here.."/>
            <textarea ng-model="emailBody" placeholder="Email body here..">
            </textarea>
            <h2> {{emailBody}} </h2>
        </div>
    </body>
</html>

Upvotes: 3

Related Questions