-1

我有這個JS代碼服務不是一個簡單的控制器工作

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


app.service('testService', function(){ 
    this.sayHello= function(text){ 
    return "Service says \"Hello " + text + "\""; 
    }; 
    this.sayGoodbye = function(text){ 
    return "Service says \"Goodbye " + text + "\""; 
    }; 
}); 


app.controller('AboutCtrl', ['testService', function ($scope, $location, $http) { 


    $scope.fromService = testService.sayHello("World"); 
    $scope.toService = testService.sayGoodbye("World"); 
}]); 

,在我的HTML我有這個 .... ... 喜{{fromService}} ... ... 控制檯中沒有錯誤,頁面只是空白。

+0

你有沒有在你的HTML中的任何地方放置一個'ng-app'聲明? – Makoto

+0

在app.controller('AboutCtrl',['testService',function($ scope,$ location,$ http){'line。')中添加'testService'作爲依賴項。 –

回答

5

請看看AngularJs文檔「使用依賴注入」。

正確的方法:

app.controller('AboutCtrl', ['$scope', '$location', '$http', 
'testService', function ($scope, $location, $http, testService) { 
     $scope.fromService = testService.sayHello("World"); 
     $scope.toService = testService.sayGoodbye("World"); 
}]); 
1

你沒有正確注射服務。

app.controller('AboutCtrl', ['$scope', '$location', '$http', 
'testService', function ($scope, $location, $http, testService) { 

     $scope.fromService = testService.sayHello("World"); 

     $scope.toService = testService.sayGoodbye("World"); 

}]); 

而且在你HTML你應該添加ng-app="app"ng-controller到especify控制器。

<!DOCTYPE html> 
<html ng-app="app"> 
    <head></head> 
    <body ng-controller="AboutCtrl"> 
     <p>Hi {{fromService}}</p> 

    <!-- Also place here your JS files.-->> 
    </body> 
</html> 
1

晚餐容易,其實您注射服務錯誤的地方進行檢查:

app.controller('aboutCtrl', function ($scope, $location, $http, testService) { 
$scope.fromService = testService.sayHello("World"); 
$scope.toService = testService.sayGoodbye("World"); 
}); 
2

你可以注入你的服務通過這些方式來控制器。

嵌入式陣列註釋

app.controller('MyController', ['$scope', 'testService', function($scope, testService) { 
    // ...Code here 
}]); 

$注入性註釋

var MyController = function($scope, testService) { 
    // ... 
} 
MyController.$inject = ['$scope', 'testService']; 
app.controller('MyController', MyController); 

隱註釋

app.controller('MyController', function($scope, testService) { 
    // ... 
}); 

如果你想知道哪一個是首選然後閱讀這Dependency Injection

相關問題