数据绑定在我的AngularJS应用程序中不起作用

Data binding not working in my AngularJS app

本文关键字:不起作用 应用程序 AngularJS 我的 数据绑定      更新时间:2023-09-26

我有以下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>

我引用了textArea中的emailBody数据,但它没有绑定关联的数据。它只是按字面意思键入{{emailBody}}。

我做错了什么?

假设您是第一次使用Angular,您可能希望使用不带值的"ng-app"参数,该参数将设置注入上下文,而不将其映射到命名的应用程序控制器(在您的示例中缺少)。还要注意,您的script标记的src参数缺少一个右引号。

以下是您的示例,其中包含这两个修复程序,工作正常。

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

尝试将以下内容添加到java脚本文件中。

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

它定义了您要绑定的应用程序/模块和emailBody字段。

然后,您可以添加对以下脚本的引用,也可以添加一个ng控制器来引用控制器。

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