簡體   English   中英

AngularJS-如何將數據從View(HTML)傳遞到Controller(JS)

[英]AngularJS - How to pass data from View (HTML) to Controller (JS)

我真的是AngularJS的新手。 我想將某些對象從View(HTML)傳遞到我的控制器(JS)。 實際上,我的客戶將以HTML格式向我發送數據,我必須獲取該數據並在控制器中處理該數據,然后在屏幕上顯示處理后的輸出。 他將使用一種稱為ServiceNow的后端技術-https: //www.servicenow.com/

我看到的所有解決方案都有一些事件,例如單擊事件或更改事件,但就我而言,這必須在頁面加載時完成。

我正在使用隱藏的輸入類型來將數據傳遞給控制器​​,似乎不起作用。 那么我還有其他方法可以做到這一點嗎? 這是我嘗試使用的代碼

<div ng-controller="progressController" >
  <input type="hidden" value="ABCD" ng-model="testingmodel.testing">
</div>
app.controller('progressController', function($scope) {
  console.log($scope.testingmodel.testing);
});

當我在Controller中console.log我的變量時,它說未定義。

您應該使用ng-change或$ watch

<div ng-controller="progressController" >
  <input type="hidden" value="ABCD" ng-model="testingmodel.testing" ng-change="change()">
</div>
app.controller('progressController', function($scope) {
   $scope.change = function(){
       console.log($scope.testingmodel.testing);
   }

});

要么:

app.controller('progressController', function($scope) {
   $scope.$watch('testingmodel.testing', function(newValue, olValue){
       console.log(newValue);
   }

});

如果使用ng-change,則僅當用戶更改UI中的值時才調用該函數。 如果仍然使用$ watch,則調用該函數。

您不能使用value屬性來設置或獲取任何控件的值,an​​gularJS使用ngModel來設置或獲取值。

在這里你應該這樣嘗試

app.controller('progressController', function($scope) {
  //from here you can set value of your input
  $scope.setValue = function(){
      $scope.testingmodel = {}
      $scope.testingmodel.testing = 'ABCD';
  }

  //From here you can get you value 
  $scope.getValue = function(){
   console.log($scope.testingmodel.testing);
  }
});

如果您想從html端進行綁定,則應嘗試如下所示

<input type="text" ng-model="testingmodel.testing"> 
<input type="hidden" ng-model="testingmodel.testing">

您正在做console.log(...)太早了。 目前,您的控制器沒有該視圖中的任何信息。

第二個問題是您將視圖綁定到控制器中的變量,而不是相反。 $scope.testingmodel.testingundefined ,顯然它將視圖中的值變為undefined

使用ng-init初始化模型,並使用控制器的鈎子$postLink獲取所有初始化后的值。

像這樣

<div ng-controller="progressController" >
    <input type="hidden" ng-model="testingmodel.testing" ng-init="testingmodel.testing = 'ABCD'">
</div>
app.controller('progressController', function($scope) {
    var $ctrl = this;

    $ctrl.$postLink = function() {
        console.log($scope.testingmodel.testing);
    };
});

編輯:額外提示

我不建議使用$scope來存儲數據,因為它會使向新角度的遷移更加困難。

請改用控制器。

像這樣:

<div ng-controller="progressController as $ctrl" >
    <input type="hidden" ng-model="$ctrl.testingmodel.testing" ng-init="$ctrl.testingmodel.testing = 'ABCD'">
</div>
app.controller('progressController', function() {
    var $ctrl = this;

    $ctrl.$postLink = function() {
        console.log($ctrl.testingmodel.testing);
    };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM