[英]Accessing pre-filled input fields in controllers
What is the best way to access pre-filled input fields values in angularjs? 在angularjs中访问预填充输入字段值的最佳方法是什么? For example, how can I access the value of variable1 (which is pre-filled on pageload) within controller scope? 例如,如何访问控制器范围内的variable1的值(在pageload中预先填充)? I am using ng-model directive on the hidden input field and using $scope.formData.variable1 to access in the controller but with no luck. 我在隐藏的输入字段上使用ng-model指令,并使用$ scope.formData.variable1来访问控制器,但没有运气。 I tried searching in the web for similar issue, but most of the examples were related to accessing form field on submit or click. 我尝试在网络上搜索类似的问题,但是大多数示例与在提交或单击时访问表单字段有关。 Here is link to plnkr 这是plnkr的链接
<body ng-controller="MainController">
<h1>{{message}}</h1>
<form name="formData">
<input type="hidden" name="variable1" ng-model="formdata.variable1" value="abc" />
</form>
AngularJs Code: AngularJs代码:
(function() {
var app = angular.module("testapp", []);
var MainController = function($scope) {
console.log($scope.formData.variable1);
$scope.message = "Hello, Angular!";
};
app.controller("MainController", ["$scope", MainController]);
}());
You can do something like this. 你可以做这样的事情。 using ng-init; 使用ng-init;
<input name="data[name]"
ng-model="data.name"
ng-init="data.name='mark'" />
or 要么
You can use directive. 您可以使用指令。 something like this. 这样的事情。
app
.directive('ngDefaultValue', function() {
return {
restrict: 'A',
controller: function($scope, $element, $attrs, $parse) {
$parse($attrs.ngModel).assign($scope, $attrs.ngDefaultValue || $attrs.value);
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.