如何在angular中使用ng click

how to use ng-click in angular

本文关键字:ng click angular      更新时间:2023-09-26

我用angular编写了一个litlle程序。当我转到网址时:http://localhost:8080/api/v1/projects(一个get请求),我在浏览器中看到一个json表。我想做的是,有一个这些对象的"列表"。我的意思不仅仅是json,而是向用户展示。

这些是我的文件:

index.html、index.js和service.js

service.js

var app = angular.module('app');
app.service('apiService', ['$http', function($http) {
  this.get = function() {
    return $http.get("http://localhost:8080/api/v1/projects");
  };
  this.delete = function(id) {
    return $http.delete("http://localhost:8080/api/v1/projects/{id}", id);
  }
  this.post = function(data){
    return $http.post("http://localhost:8080/api/v1/projects", data);
  }
}]);

index.js

app.controller('controller', ['$scope', 'apiService', function($scope, apiService) {
  var vm = this;
  var getData = apiService.get().success(function(data) {
    vm.data = data;
  }); 
}]);

index.html

  <!DOCTYPE html>
  <html lang="en" ng-app="myApp">
  <head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javavscript" src="angular.min.js"></script>
  <script type="text/javavscript" src="index.js"></script>
  <script type="text/javavscript" src="service.js"></script>
  </head>
  <body>
  <div ng-controller="controller as ctrl">
  <div ng-repeat="data in ctrl.data">{{data.name}}</div>
  </div>
  </body></html>

如果我去我的URL而不是看到json 的列表,你能告诉我如何在我的代码中包含ng-click(或任何显示结果的方法)以获得文档列表吗

谢谢!

您可以创建一个$state。我不太确定这是否是你想要实现的,但首先你可以在https://localhost:8080/home。。然后你可以用ng点击来制作一个按钮:

<input type="submit" ng-click="redirectTo("http://localhost:8080/api/v1/projects")"/>

在控制器中:

app.ctrl('HomeCtrl', ["$scope", "$state", function($scope,$state){
  $scope.redirectTo = function(url){
    window.location.href = url;//This because i dont know the state your trying to go to..
  }
}])

然后在这之后会重定向。然后现在,如果你想显示网址,你可以在该页面上这样做:

<input type="submit"
 ng-click="getJSON"/>
app.controller('JSONCtrl', ["$scope","apiService" function($scope,apiService){
  $scope.getJSON = function(){
    apiService.get().then(function(sucess){
     //Sucess Method..
    }).catch(function(err){
     //Error..
    })
  }
}])