如何使用href文本在ng-click中调用表单函数?

时间:2014-11-03 16:09:32

标签: javascript angularjs xmlhttprequest angularjs-scope angularjs-ng-click

是否可以使用 href 文本值作为搜索变量search()调用相同的函数$scope.keywords

function customersController($scope, $http) {
  $scope.search = function() {
    $scope.url = 'http://www.vanmaram.com/json_result.php?en=' + $scope.keywords; // The url of our search
    $http.get($scope.url).
    success(function(data, status) {
      $scope.status = status;
      $scope.data = data;
      $scope.result = data; // Show result from server in <li> element
      $scope.suggetionresult = null;
    }).
    error(function(data, status) {
      $scope.data = data || "Request failed";
      $scope.status = status;
    });
  };
  $scope.suggestword = function(argument) {
    $scope.url = 'http://www.vanmaram.com/ajax_json_suggestion.php?en=' + $scope.keywords; // The url of our search
    $http.get($scope.url).
    success(function(data, status) {
      $scope.status = status;
      $scope.data = data;
      $scope.suggetionresult = data; // Show result from server in <li> element
      $scope.result = null;
    }).
    error(function(data, status) {
      $scope.data = data || "Request failed";
      $scope.status = status;
    });
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
  <form style="position:relative;" ng-submit="search()">
    <input type="search" placeholder="Type english word" ng-model="keywords" ng-change="suggestword()">
    <input type="submit" value="Search">
  </form>
  <ul ng-if='result.length'>
    <li ng-repeat="word in result | limitTo:9">{{ word }}</li>
  </ul>
  <div id="suggestion" ng-if='suggetionresult.length > 1'>
    Suggestions: <a ng-repeat="word in suggetionresult | limitTo:9" ng-click="search()">{{ word }}</a>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您可以在搜索功能中添加可选参数。

$scope.search = function(searchUrl) {
    //Check for searchUrl, otherwise use keywords.
    var searchUrl = typeof(searchUrl) != 'undefined' ? searchUrl : $scope.keywords;

    $scope.url = 'http://www.vanmaram.com/json_result.php?en=' + searchUrl;
    $http.get($scope.url).
        success(function(data, status) {
            $scope.status = status;
            $scope.data = data;
            $scope.result = data; // Show result from server in <li> element
            $scope.suggetionresult = null;
        }).
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;
        });
};

然后ng-click="search(word)"