2017-07-18 5 views
0

私は角度のjsのボタンクリックで$ http Getサービスを呼び出そうとしています。しかし、私は次のように私のコードスニペットがある...結果に表示するデータを取得していない午前: -http getサービスを呼び出し、ボタンクリック時のangularjsのdivでその応答を表示する方法は?

<button ng-controller="myCtrl6" ng-click="search()">Click</button> 
<p ng-controller="myCtrl6"> 
    {{results}} 
    {{fail}} 
</p> 
var app = angular.module("myApp", []); 
app.controller('myCtrl6', ['$scope', '$http', function ($scope, $http) { 
    $scope.results = ""; 
    $scope.fail = "f"; 
    $scope.search = function() { 
    $http.get('welcome.html', {}, function(response) { 
     $scope.results = response.data; 
    }, function (failure) { 
     console.log("failed :(", failure); 
    }); 
    } 
}]); 

のwelcome.html

Hello World 
+0

を書くのか? – L4reds

+0

これをチェックしてくださいhttps://stackoverflow.com/questions/41169385/http-get-success-is-not-a-function –

+0

then()関数が必要です! –

答えて

1

これは、$ HTTPの適切な使用であります

$http({ 
    method: 'GET', 
    url: '/someUrl' 
}).then(function successCallback(response) { 
    // in your case 
    $scope.results = response.data; 
    }, function errorCallback(response) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
    }); 

または

$http.get('/someUrl', config).then(successCallback, errorCallback); 

よりよいこのためのサービスを行います。これを行うことにより、あなたがアクセスすることができ、(メインコンテナ)のdivの内側にあなたのボタンとpタグをラップ編集

+0

で$ scope.searchを呼び出しました。内部のコントローラー? –

+0

私は答えを –

+0

更新しました。そのserviceNameは何ですか...私はそれの代わりに何を指定すべきですか? –

0

コントローラ

var app = angular.module("myApp", []); 
app.controller('myCtrl6', ['$scope', 'ServiceName', function ($scope, serviceName) { 
    $scope.search = function() { 
    serviceName.search().then(function(response) { 
     $scope.results = response.data; 
    }); 
    } 
}]); 

app.factory('ServiceName', function() { 
    return { 
    search: search 
    }; 

    function search() { 
    return $http.get('/someUrl', config); 
    } 
}); 

をあなたのコントローラは、そのメインコンテナの内側でのみスコープします。

<div ng-controller="myCtrl6"> 
     <p >{{results}} 
     {{fail}} 
     </p> 
     <button ng-click="search()">Fetch Data</button> 
</div> 

そしてscript.jsファイルにあなたは$ scope.search関数を呼び出した

$scope.search = function() {      
      $http.get('welcome.html') 
      .success(function(response) { 
      $scope.results = response; 
      }) 
      .error(function(error) { 
      console.log("error is : " + JSON.stringify(error)) 
      }) 
    } 
+0

ありがとうございました –

関連する問題