Angular JS绑定不起作用

时间:2015-07-08 11:22:39

标签: javascript angularjs

我不确定以下代码中出现了什么问题 - 但它似乎不起作用。有人可以帮忙吗?

<body ng-controller="MyFunction">
        <script>
            function MyFunction($scope) {
                $scope.author = {
                    'name':'Test',
                    'title': 'Mr',
                    'Job': 'SDE'
                }
            }
        </script>
       <h2> {{author.name}} </h2>
       <h2> {{author.title + " " + author.Job}} </h2> 
    </body>

2 个答案:

答案 0 :(得分:0)

你在这里。你在angularjs的结构上是不正确的,我没有看到ng-app和错误来声明控制器:

&#13;
&#13;
angular.module('app', []).controller('MyFunction', function($scope) {
  $scope.author = {
    'name': 'Test',
    'title': 'Mr',
    'Job': 'SDE'
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app='app' ng-controller="MyFunction">
  <h2> {{author.name}} </h2>

  <h2> {{author.title + " " + author.Job}} </h2> 
</body>
&#13;
&#13;
&#13;

希望这有帮助。

答案 1 :(得分:0)

您的代码有几处出问题。您缺少ng-app声明,缺少用于该声明的module,而您没有正确注册controller。您处于工作状态的示例:

&#13;
&#13;
function authorInfoController() {
  this.author = {
    name: 'Amadeus Smith',
    title: 'Prof.',
    job: 'Super Senior Cloud Advisor Managment Consultant'
  };
}

angular.module("myApp", [])
  .controller("AuthorInfoCtrl", authorInfoController);
  
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>

<div ng-app="myApp" ng-controller="AuthorInfoCtrl as info">
  <h2>{{info.author.name}}</h2>
  <h2>{{info.author.title + " " + info.author.job}}</h2>
</div>
&#13;
&#13;
&#13;

如果您只是学习角度,我建议您a good tutorial并阅读a styleguide