2017-09-09 48 views
1

你好,我正在學習角度,並試圖綁定數據從模型來查看。但它沒有拋出任何錯誤。你可以幫我嗎。無法綁定來自控制器的數據進行查看。在控制檯沒有錯誤

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

請找Fiddler

+0

另一個有趣的答案。 https://stackoverflow.com/questions/11605917/this-vs-scope-in​​-angularjs-controllers –

回答

3

變化ng-controller="emp"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> 

小提琴:https://jsfiddle.net/vedp/duhfgbb9/1/

+1

@ shams.kool {{name}}將不起作用,因爲'name'不是$ scope變量。 – Ved

+0

@Ved是的,它的工作。謝謝但你能解釋爲什麼嗎?它與我正在使用的角度版本有關。 – Megh

+0

@Ved你是對的。我在想別的東西。 –

0

您AR Ë失蹤$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>

2

您應該使用controller as syntax這裏,

變化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>

+0

是的,它的工作。 :) – Megh

相關問題