AngularJS:控制器内定义变量的值未正确显示

时间:2015-01-13 22:35:17

标签: javascript angularjs angularjs-controller

我正在学习角度..我试图通过复数运行一个小例子,但无法呈现正确的输出.. http://plnkr.co/edit/cYEDSW3FrAKeh1SBjUVN?p=preview HTML

<!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="angular.js@*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainController">
    <h1>{{text}}</h1>

    <div>
      <div>First name: {{person.firstName}}</div>
      <div>Last name: {{person.lastName}}</div>
      <img ng-src="person.imageSrc" title="{{person.firstName}} {{person.lastName}}">
    </div>
  </body>

</html>

的script.js

var MainController = function($scope) {

  var person = {
    firstName: "Ajay",
    lastName: "Sattikar",
    imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"

  };

  $scope.text = "Hello Angular!";
  $scope.person = person;

};

我无法弄清楚为什么角度变量会显示为普通文本而不是其指定值。专家,请帮助......

2 个答案:

答案 0 :(得分:2)

您的代码中需要更改一些内容

  1. 您需要创建一个角度模块
  2. var app = angular.module('app', []);
    

    2添加指令到html元素

    <html ng-app='app'>
    
    1. 需要针对角度模块注册MainController,如下所示:
    2. app.controller('MainController', function($scope) {
      
        var person = {
          firstName: "Ajay",
          lastName: "Sattikar",
          imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
      
        };
      
        $scope.text = "Hello Angular!";
        $scope.person = person;
      
      });
      

      这是一个有效的演示 - http://plnkr.co/edit/i9N2OC75EGZwUTDcKtLB?p=preview

答案 1 :(得分:0)

你错过了几步:

1.声明你的应用

<html ng-app='myApp'>

2。在您的app模块中声明您的控制器:

angular.module('myApp', [])
 .controller('MainController', function($scope) {

     var person = {
         firstName: "Ajay",
         lastName: "Sattikar",
         imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
     };

     $scope.text = "Hello Angular!";
     $scope.person = person;
})