2016-08-12 75 views
1

這裏是我的模塊:角度支柱的要求不工作不工作

angular.module('ngDetails', [']) 
.constant('API', 'http://myserver.com/dir/api') 
.controller('carDetails', carDetails) 

這裏是我的控制器:

function carDetails($scope, CarDetailService) { 
    CarDetailService.getCar().success(function(details) { 

    $scope.details = details; 

    carID = $scope.details['ID']; 

    $scope.approve = function($scope, $http, API, Message) { 
     $http.post(API + '/car/' + carID , { Message: Message }). 
     success(function(data) { 
     $scope.approve = data; 
     }) 
    } 

    }); 

這裏是我的HTML:

<div ng-controller="carDetails"> 
    <textarea placeholder="Message" ng-model="Message"></textarea> 
    <button ng-click="approve()">Approve</button> 
</div> 

我試圖要做的就是向我的API發送一個post請求,併發送一條消息,讓用戶在他們點擊「批准」之前將其放入textarea框中utton。但是當我點擊「批准」按鈕時,我收到一個錯誤 - 「無法讀取'm。$ scope.approve'中未定義的屬性'post'。我該如何解決這個問題?

在此先感謝。

回答

1

那是因爲您需要在構造函數中需要DI項目,而不是在批准函數中。

function carDetails($scope, CarDetailService, $http, API, Message) { 
    CarDetailService.getCar().success(function(details) { 

    $scope.details = details; 

    carID = $scope.details['ID']; 

    $scope.approve = function() { 
     $http.post(API + '/car/' + carID , { Message: Message }). 
     success(function(data) { 
     $scope.approve = data; 
     }) 
    } 

    }); 
+1

Aaaah,這是我做錯了什麼。很高興知道。 – agon024

0

當你與角度的服務或您自己構建的服務工作,要在控制器使用他們的服務,你需要將它們注入

$scope.approve = function($scope, $http, API, Message) { 
     $http.post(API + '/car/' + carID , { Message: Message }).//$http? 
     success(function(data) { 
     $scope.approve = data; 
     }) 

進樣這樣

function carDetails($scope, CarDetailService,$http) { 
    CarDetailService.getCar().success(function(details) { 

    $scope.details = details; 

    carID = $scope.details['ID']; 

    $scope.approve = function($scope, $http, API, Message) { 
     $http.post(API + '/car/' + carID , { Message: Message }). 
     success(function(data) { 
     $scope.approve = data; 
     }) 
    } 

    });