2013-06-20 23 views
1

所以我試圖將我的應用程序從jQuery轉換爲angularjs。包括通過angularjs在DOM元素中提取數據

我想創建一個動態顯示框,顯示基於用戶輸入從mySQl數據庫獲取的數據。

我的PHP腳本返回一個JSON。

設置我<div><input>場:

<input type="text" ng-model="testActivator"> 

<div class="Container" ng-show="Activator.length" ng-controller="ContainerCtrl"> 
     <p>{{fetchData(testActivator)}}</p> 
</div> 

而且我創造我的控制器:

function ContainerCtrl($scope,$http){ 

$scope.item = [{}]; 

$scope.fetchData = function($input){ 

    $http.post("../sys/core/fetchPacking.php",{ 
     'val': $input 
    }).success(function(data,status){ 
     $scope.item.push(data.key); 
    }); 

    return $scope.item; 

} 

$scope.hide = function(){ 
    return false; 
} 

} 

現在,下面和問題上來:

  • 當我通過給<input>提供輸入來啓動腳本,它會產生一些東西這對我來說看起來像是一個無限循環:返回的數據將一次又一次地在框中傳遞。我如何防止這種情況,爲什麼?
  • 而不是正確的值,腳本返回null。我的錯在哪裏?

p.s.問題#1還會引發另一個問題:我如何看我的返回值。直到今天,我將通過console.log()解析它到控制檯。但是,當這個循環運行時,這是行不通的。

回答

1

你的代碼有幾個問題。

首先您的testActivator需要位於與ContainerCtrl相同範圍內。

我想你想在輸入值改變時調用fetchData?那麼你應該使用ng-change指令。

在表達式中調用fetchData函數沒有任何意義。 fetchData函數應該發出請求並將結果數據放入作用域中的一個變量中。 裏面表達的你就可以顯示該獲取的數據:

<div class="Container" ng-controller="ContainerCtrl"> 
    <input type="text" ng-model="testActivator" ng-change="fetchData(testActivator)"> 

    <div> 
     <p ng-repeat="item in items">{{item}}</p> 
    </div> 
</div> 

而且你的控制器看起來應該是這樣的:

function ContainerCtrl($scope,$http) { 
    $scope.items = []; 
    $scope.fetchData = function(input){ 
     $http.post("../sys/core/fetchPacking.php",{ 
      'val': input 
     }).success(function(data,status){ 
      $scope.items.push(data.key); 
     }); 
    } 
} 

我想你應該通過AngularJS教程工作: http://docs.angularjs.org/tutorial/

1

你需要 「看」 testActivator在您的控制器的變化......

$scope.$watch('testActivator', function (testActivator) { 
    $scope.fetchData(testActivator); 
}); 

$scope.fetchData = function (testActivator) { 
    $http.post("../sys/core/fetchPacking.php", {'val': testActivator}) 
     .success(function (data, status) { 
      $scope.item.push(data.key); 
     }); 
}; 

而且testActivator輸入需要的ContainerCtrl範圍內...

<div class="Container" ng-show="Activator.length" ng-controller="ContainerCtrl"> 
    <input type="text" ng-model="testActivator"> 

    <p ng-repeat="item in items">{{item | json}}</p> 
</div> 

否則,您可以使用角度的「點規則」來解決父級和子級示波器之間的可見性問題:

基本上,只是改變testActivator爲類似foo.testActivator