angularjs控制器不起作用

时间:2015-11-26 04:29:25

标签: angularjs

以下代码不会在屏幕上显示firstName和lastName。任何人都可以指出我错过了什么?谢谢。

<body ng-app="myApp">
<div  ng-controller="myCtrl">
  Full Name: {{name.firstName + " " + name.lastName}}
</div>

<script src="../bower_components/angular/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
 var name={
  firstName: "John",
  lastName: "Doe"
 }
 this.name=name;
});

1 个答案:

答案 0 :(得分:4)

我认为你正在尝试将控制器作为语法。如果是这样

<div  ng-controller="myCtrl as myctrl">
  Full Name: {{myctrl.name.firstName + " " + myctrl.name.lastName}}
</div>

否则你必须在$ scope对象中注入$ scope和set name变量。

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope',function($scope) {
    var name={
       firstName: "John",
       lastName: "Doe"
    }
    $scope.name=name;
}]);