1

Hello I am learning angular and trying to bind data from model to view. But its not throwing any error. Can you help me.

<div ng-app ="myApp" ng-controller="emp"> 
 Hello {{emp.name}}, I am happy that you are getting a salary of{{emp.salary}}.
</div> 

var app = angular.module("myApp", []);

app.controller('emp', function(){
 this.name = "John";
 this.salary = 4500;
});

Please find Fiddler

Megh
  • 145
  • 9
  • Another interesting answer here. https://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers – shams.kool Sep 09 '17 at 08:04

3 Answers3

3

Change ng-controller="emp" to ng-controller="emp as emp"

<div ng-app ="myApp" ng-controller="emp as emp"> 
     Hello {{emp.name}}, I am happy that you are getting a salary of{{emp.salary}}.
    </div> 

Fiddle: https://jsfiddle.net/vedp/duhfgbb9/1/

Ved
  • 11,837
  • 5
  • 42
  • 60
  • 1
    @shams.kool {{name}} will not work as `name` is not $scope variable. – Ved Sep 09 '17 at 07:49
  • @Ved Yes it worked. Thanks But can you explain why? It is something related to angular version I am using. – Megh Sep 09 '17 at 07:58
  • 1
    @Megh please see this question https://stackoverflow.com/questions/22806681/difference-between-this-and-scope-in-the-controller or just search it google there are lot of related answers. – shams.kool Sep 09 '17 at 08:02
  • 1
    @Megh it is not releated to Angular version. with Controller As syntax work with controllers as classes.Check this answe: https://stackoverflow.com/questions/21287794/angularjs-controller-as-syntax-clarification – Ved Sep 09 '17 at 08:02
1

You should use controller as syntax here,

change to ng-controller="emp as emp"

DEMO

var app = angular.module("myApp", []);

app.controller('emp', function(){
 this.name = "John";
 this.salary = 4500;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ="myApp" ng-controller="emp as emp"> 
 Hello {{emp.name}}, I am happy that you are getting a salary of{{emp.salary}}.
</div>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

You are missing $scope

var app = angular.module("myApp", []);

app.controller('emp', ['$scope', function($scope) {
  $scope.empData = {
    name: "John",
    salary: 4500
  }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="emp">
  Hello {{empData.name}}, I am happy that you are getting a salary of{{empData.salary}}.
</div>
brk
  • 48,835
  • 10
  • 56
  • 78