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

AngularJS: values of defined variables inside controller are not getting displayed correctly

我正在学习 angular..我已经尝试 运行 通过 pluralsight 的一个小例子,但无法呈现正确的输出.. 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;

};

我无法弄清楚为什么 angular 变量显示为普通文本而不是其分配的值。专家,请帮助...

您的代码中有几处需要更改

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

2 向 html 元素添加指令

<html ng-app='app'>
  1. 需要像这样针对 angular 模块注册 MainController
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. 声明您的应用程序

<html ng-app='myApp'>

2。在您的应用程序模块中声明您的控制器:

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;
})