2017-05-26 128 views
1

我有我的頁面元素像這樣如何將數據從AngularJS控制器發送到其服務?

<div ng-app="myApp" class="ng-cloak" ng-controller="MyController as ctrl"> 
     <div class="item" ng-repeat="i in ctrl.items">     
      <h3>Some text...</h3> 
      <p ng-bind="i.id"></p> 
      <button ng-click="alertValue(i.id)">DETAILS</button></p>     
     </div> 
</div> 

我的控制器看起來是這樣的,有一個方法

'use strict'; 

    App.controller('MyController', ['$scope', 'Item', function ($scope, Item) { 
      $scope.alertValue = function (id) { 
       alert('clicked:' + id); 
      } 
    } 

的正常工作,我得到id爲警報。但是,我如何將這個ID從控制器發送到我的服務?我嘗試了幾個教程,但他們都不一樣,我完全迷失了。任何人都可以用簡單的方式向我解釋這一點,並展示如何做到這一點? 可能需要提供一些其他信息?謝謝。

+7

最好去通過文檔https://docs.angularjs.org/guide/services –

+0

我會的,但我希望得到一些簡單的例子也是如此。 Thanx先生,Mr_Perfect。很好的登錄btw。 – Bobby

+0

你的服務是什麼?項目? –

回答

2

我儘量不使用示波器,因此我會在控制器上爲該點擊創建一個function。那麼這只是一個你想做的事情。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script> 
 
    angular.module('my-app', []) 
 
    .service('Items', function() { 
 
    return { 
 
     doWork: function(id) { 
 
     console.log(id); 
 
     } 
 
    }; 
 
    }) 
 
    .controller('ItemsCtrl', function(Items) { 
 
    var vm = this; 
 
    vm.items = [ 
 
     { id: 1, name: 'Foo' }, 
 
     { id: 2, name: 'Bar' }, 
 
     { id: 3, name: 'Baz' }, 
 
    ]; 
 
    
 
    vm.doWork = function(id) { 
 
     Items.doWork(id); 
 
    }; 
 
    }); 
 
</script> 
 

 

 

 
<div ng-app="my-app"> 
 
    <div ng-controller="ItemsCtrl as ctrl"> 
 
    <ul> 
 
     <li ng-repeat="item in ctrl.items"> 
 
     {{item.name}} 
 
     <button ng-click="ctrl.doWork(item.id)">Do Work</button> 
 
     </li> 
 
    </ul> 
 
    </div> 
 
</div>

1

您必須使用$http服務。 $http服務便於與遠程HTTP服務器進行通信。

$http服務使用then方法爲了附加callback

then()方法有兩個參數:一個successerror回調將與響應對象被調用。

使用then()方法,將callback函數附加到返回的promise

事情是這樣的:

app.controller('MainCtrl', function ($scope, $http){ 
    $http({ 
    method: 'GET', 
    url: 'api/url-api' 
    }).then(function (success){ 

    },function (error){ 
    }); 
} 

見參考here

快捷方法也可用。

$http.get('api/url-api').then(successCallback, errorCallback); 

function successCallback(response){ 
    //success code 
} 
function errorCallback(error){ 
    //error code 
} 
1

您必須在控制器內部注入服務以將一些數據傳遞給它。

app.controller.js

App.controller('MyController', ['$scope', 'ItemService', function ($scope, ItemService) { 
     $scope.alertValue = function (id) { 
      ItemService.id = id;  
     } 
} 

請參考this的更多信息,創建和在角註冊的服務。

相關問題