如何在控制器中获取输入值?

时间:2015-11-15 18:42:16

标签: angularjs http search

我尝试为应用构建实时搜索。我做了一个更改,记录输入(ng model searchLive)并重新加载http请求。但$ scope.searchlive返回undefined,ng更改有效。建议?

我的控制员:

Status : 1 = Open, 2 = Closed, 3 = In Progress

})

我的模板

.controller('searchCtrl', function($scope, $http) {
$scope.change = function() {
    console.log($scope.searchLive);
    $scope.loadData();
}



$scope.loadData = function () {
        $http.get("http://example.com/?json=get_search_results&include=id,title&search="+ $scope.searchLive +"", {cache:false})
        .success(function(data) {$scope.zoekresultaat = data.posts; });
    };

2 个答案:

答案 0 :(得分:0)

问题是嵌套的范围。 http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html

模板:

 <div class="list">
        <div class="item item-input-inset">
            <label class="item-input-wrapper"
                <input type="text" placeholder="zoek" ng-change="change()" ng-model="search.term" >
            </label>
        </div>            
        <a class="item " href="#/app/post/{{item.id}}" ng-repeat="item in zoekresultaat ">
          <h2>{{item.title}}</h2>
          <p>{{categories[0].title[}}</p>
        </a>
      </div>

控制器:

.controller('searchCtrl', function($scope, $http) {

var pendingTask;

if ($scope.search === undefined) {
  $scope.search = { term:  ""};
  fetch();
}

$scope.change = function() {
  if (pendingTask) {
    clearTimeout(pendingTask);
  }
  pendingTask = setTimeout(fetch, 1000);
};

function fetch() {
  $http.get("http://www.example.com/?json=get_search_results&search=" + $scope.search.term + "&include=id,title,categories")
    .success(function(response) {$scope.zoekresultaat = response.posts; });

}

})

答案 1 :(得分:0)

您是否尝试使用控制器范围?例如,

 <div ng-controller="searchCtrl as ctrl">...</div>

在你的js文件中,你使用它而不是$ scope 不要忘记在依赖项中注入$ http,如

.controller('searchCtrl',['$http',function($http){

    this.searchLive = "";     

    this.change = function() {
        console.log(this.searchLive);
        this.loadData();
    }

    this.loadData = function () {
        var datas = []; 
        $http.get("http://example.com/?json=get_search_results&include=id,title&search="+ $scope.searchLive +"", {cache:false})
        .success(function(data) {datas = data.posts; });
        this.zoekresultaat = datas;
    };
}]);

我使用局部变量没有任何范围冲突

你的html变成了

<div class="list">
<div class="item item-input-inset">
    <label class="item-input-wrapper">
        <input type="text" placeholder="zoek" ng-model="ctrl.searchLive" ng-change="ctrl.change()">
    </label>
</div>            
<a class="item " href="#/app/post/{{item.id}}" ng-repeat="item in ctrl.zoekresultaat ">
  <h2>{{item.title}}</h2>
  <p ng-bind-html="item.excerpt"></p>
  <p ng-show="item.excerpt == 0">Geen beschrijving</p>
</a>

我希望它能帮到你