2016-11-28 46 views
0

我想獲得沒有任何按鈕操作的angularjs隱藏字段值。我在angularjs新的,如果這個解決方案提供的任何鏈接請發送到我下面如何在沒有任何按鈕操作的情況下獲取Angularjs隱藏字段值?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
<div ng-app ng-controller="TestController"> 
    <input type="hidden" name="id" ng-model="id" ng-init="id=12"></input> 
</div> 
<script> 
function TestController($scope) { 

     alert($scope.id); 
} 
</script> 
+0

觀察什麼沒有奏效? – Sajeetharan

+0

我收到未定義的值。爲什麼? – Rijo

回答

2

的問題是,在控制器警報NG-INIT被置之前被調用,

試試這個,

app.controller('myController', function($scope,$timeout) { 
    $timeout(function() { 
     alert($scope.id); 
    }) 
}); 

DEMO

+0

謝謝工作正常 – Rijo

1

給出

代碼看來這個問題是id變量初始化之前alert(...)調用執行。

這似乎是工作

function TestController($scope, $timeout) { 
 
     $timeout(function(){alert($scope.id);},0, true); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app ng-controller="TestController"> 
 
    <input type="hidden" name="id" ng-model="id" ng-init="id=12">  
 
</div>

+0

謝謝工作正常 – Rijo

1

您可以創建初始化函數,並通過$watch

function TestController($scope) { 
 
    this.init = function() { 
 
    $scope.id = 12; 
 

 
    $scope.$watch('id', function(value, oldValue) { 
 
     console.log('changed', $scope.id) 
 
    }); 
 
    console.log('id has been initialized'); 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app ng-init="vm.init()" ng-controller="TestController as vm"> 
 
    <input type="hidden" name="id" ng-model="id"> 
 
    <input type="text" placeholder="just test input" name="other" ng-model="id"> 
 
</div>

相關問題