Jun Q
Jun Q

Reputation: 443

angularjs controller doesn't work

The following code does not display firstName and lastName on screen. can any one point out what am I missing? Thanks.

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

Upvotes: 1

Views: 65

Answers (1)

Subin Sebastian
Subin Sebastian

Reputation: 10997

I think you are trying controller as syntax.If so

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

Otherwise you have to inject $scope and set name variable in $scope object.

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

Upvotes: 4

Related Questions