为什么这个Angular ng-bind不会绑定到ng-controller?

时间:2016-12-10 00:13:58

标签: javascript html angularjs

我正在学习Angular.js。我想创建一个sendfile,用户可以在其中看到输出已填写完毕。

这是form

test.html

这是<head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0-rc.2/angular.js"></script> <script src="test.js"></script> </head> <body ng-app="charter"> <div id="layout-wrapper" ng-controller="graphicLanguageCTRL"> <form id="graphic-language" ng-controller="graphicLanguageCTRL" novalidate> <h3>Language</h3> <input type="text" name="headline" placeholder="Headline" ng-model="graphic.hed"> <br> </form> </div> <h1 class="graphic-title" ng-bind="graphic.hed"></h1> </body>

test.js

我希望var app= angular.module("charter",[]); app.controller("graphicLanguageCTRL",function($scope){ $scope.master= { hed: '' }; }); 标记中输入的内容在input标记中可见。但是当我输入h1标记时,input标记中没有任何内容。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您的代码中存在一些错误:

  • 您正在控制器之外使用ng-bind
  • 您正在初始化graphicLanguageCTRL两次
  • 在您的脚本中,您设置了错误的变量名称

以下是固定代码:

HTML

<body ng-app="charter">
  <div id="layout-wrapper" ng-controller="graphicLanguageCTRL">
    <form id="graphic-language" novalidate>
      <h3>Language</h3>
      <input type="text" name="headline" placeholder="Headline" ng-model="graphic.hed"> <br>
    </form>
    <h1 class="graphic-title" ng-bind="graphic.hed"></h1>
  </div>
</body>

JS

var app = angular.module("charter",[]);

app.controller("graphicLanguageCTRL", function($scope){
  $scope.graphic = {
    hed : ''
  };
});

答案 1 :(得分:0)

var app = angular.module("charter",[]);
app.controller("graphicLanguageCTRL",function($scope){
    $scope.graphic = {
        hed: ''
    };
});

var app = angular.module("charter",[]);
app.controller("graphicLanguageCTRL",function($scope){
    $scope.graphic = {};
    $scope.graphic.head = ''
});

答案 2 :(得分:0)

需要注意两件事:

  • 不要嵌套并使用相同的ng-controller
  • h1移到里面 ng-controller

修正版:

var app = angular.module('charter', []);
app.controller("graphicLanguageCTRL", function($scope) {
  $scope.graphic = {
    hed: ''
  };
});
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0-rc.2/angular.js"></script>
    <meta charset="utf-8">
    <title>test</title>
  </head>
  <body ng-app='charter'>
  <div id="layout-wrapper" ng-controller="graphicLanguageCTRL">
    <form id="graphic-language" novalidate>
      <h3>Language</h3>
      <input type="text" name="headline" placeholder="Headline" ng-model="graphic.hed">
      <br>
    </form>
    <h1 class="graphic-title" ng-bind="graphic.hed"></h1>
  </div>
  </body>
</html>