0
我寫了一個簡單的Angular JS代碼,它根據一天的時間向用戶致意。它工作正常。下面的代碼給出:Angular JS object scope
var modSvc = angular.module("appName",[]);
modSvc.provider("date",function(){
var greeting;
return {
showGreeting:function(value){
greeting = value;
},
$get:function(){
//it has to return an object which can have variables and functions
return {
showDate:function(){
var date = new Date();
return date.getHours();
},
showGreetingMessage:function(){
//var date = new Date();
return greeting + ", It's "+ this.showDate();
}
}
}
};
});
modSvc.config(function(dateProvider){
var hours = dateProvider.$get().showDate();
if(hours<12)
dateProvider.showGreeting("Good morning!");
else if(hours<17)
dateProvider.showGreeting("Good afternoon!");
else if(hours<22)
dateProvider.showGreeting("Good evening!");
else
dateProvider.showGreeting("Good night!");
});
function serviceController($scope,date){
$scope.greetingMessage = date.showGreetingMessage();
}
modSvc.controller("svcController",serviceController);
如果你看到showGreetingMessage
功能它只有一行代碼是:
return greeting + ", It's "+ this.showDate();
然而showDate
功能駐留在同一水平作爲showGreetingMessage
功能。這就是爲什麼this.showDate
不應該工作,它應該給錯誤。但它工作得很好。這是怎麼回事?