AngularJS는 숨겨진 필드 값을 보내지 않습니다
특정 사용 사례의 경우 단일 형식의 "구식"을 제출해야합니다. 즉, action = ""과 함께 양식을 사용합니다. 응답이 스트리밍되어 페이지를 다시로드하지 않습니다. 일반적인 AngularJS 앱은 그런 식으로 양식을 제출하지 않지만 지금까지 다른 선택은 없습니다.
즉, Angular에서 숨겨진 필드를 채우려 고했습니다.
<input type="hidden" name="someData" ng-model="data" /> {{data}}
데이터의 올바른 값이 표시됩니다.
양식은 표준 양식처럼 보입니다.
<form id="aaa" name="aaa" action="/reports/aaa.html" method="post">
...
<input type="submit" value="Export" />
</form>
제출을 누르면 서버로 값이 전송되지 않습니다. 입력 필드를 "text"로 변경하면 예상대로 작동합니다. 내 가정은 숨겨진 필드가 실제로 채워지지 않은 반면 텍스트 필드는 실제로 양방향 바인딩으로 표시됩니다.
AngularJS로 채워진 숨겨진 필드를 제출하는 방법에 대한 아이디어가 있습니까?
숨겨진 필드에는 이중 바인딩을 사용할 수 없습니다. 해결책은 괄호를 사용하는 것입니다.
<input type="hidden" name="someData" value="{{data}}" /> {{data}}
편집 : github 에서이 스레드를 참조하십시오 : https://github.com/angular/angular.js/pull/2574
편집하다:
Angular 1.2부터 'ng-value'지시문을 사용하여 표현식을 입력의 value 속성에 바인딩 할 수 있습니다. 이 지시문은 입력 라디오 또는 확인란과 함께 사용해야하지만 숨겨진 입력에서는 잘 작동합니다.
ng-value를 사용하는 솔루션은 다음과 같습니다.
<input type="hidden" name="someData" ng-value="data" />
숨겨진 입력으로 ng-value를 사용하는 바이올린은 다음과 같습니다. http://jsfiddle.net/6SD9N
당신은 항상 사용할 수 있습니다 type=text
및 display:none;
각도 무시하기 때문에 요소를 숨겨. OP가 말했듯이 일반적 으로이 작업을 수행하지는 않지만 특별한 경우처럼 보입니다.
<input type="text" name="someData" ng-model="data" style="display: none;"/>
컨트롤러에서 :
$scope.entityId = $routeParams.entityId;
보기에서 :
<input type="hidden" name="entityId" ng-model="entity.entityId" ng-init="entity.entityId = entityId" />
Mike가 sapiensworks 에서 작성한 멋진 솔루션을 찾았습니다 . 모델의 변경 사항을 감시하는 지시문을 사용하는 것만 큼 간단합니다.
.directive('ngUpdateHidden',function() {
return function(scope, el, attr) {
var model = attr['ngModel'];
scope.$watch(model, function(nv) {
el.val(nv);
});
};
})
그런 다음 입력 내용을 바인딩하십시오.
<input type="hidden" name="item.Name" ng-model="item.Name" ng-update-hidden />
그러나 tymeJV가 제공하는 솔루션은 yycorman 이이 게시물에서 말한 것처럼 숨겨진 입력이 자바 스크립트에서 변경 이벤트를 발생시키지 않기 때문에 더 좋을 수 있으므로 jQuery 플러그인을 통해 값을 변경하면 여전히 작동합니다.
편집 변경 이벤트가 트리거 될 때 새 값을 모델에 다시 적용하도록 지시문을 변경 했으므로 입력 텍스트로 작동합니다.
.directive('ngUpdateHidden', function () {
return {
restrict: 'AE', //attribute or element
scope: {},
replace: true,
require: 'ngModel',
link: function ($scope, elem, attr, ngModel) {
$scope.$watch(ngModel, function (nv) {
elem.val(nv);
});
elem.change(function () { //bind the change event to hidden input
$scope.$apply(function () {
ngModel.$setViewValue( elem.val());
});
});
}
};
})
따라서 $("#yourInputHidden").trigger('change')
jQuery로 이벤트 를 트리거 하면 바인드 된 모델도 업데이트됩니다.
이 숨겨진 값 ()에 대해 이상한 행동을 발견했으며 작동하지 못했습니다.
After playing around we found the best way is just defined the value in controller itself after the form scope.
.controller('AddController', [$scope, $http, $state, $stateParams, function($scope, $http, $state, $stateParams) {
$scope.routineForm = {};
$scope.routineForm.hiddenfield1 = "whatever_value_you_pass_on";
$scope.sendData = function {
// JSON http post action to API
}
}])
I achieved this via -
<p style="display:none">{{user.role="store_user"}}</p>
update @tymeJV 's answer eg:
<div style="display: none">
<input type="text" name='price' ng-model="price" ng-init="price = <%= @product.price.to_s %>" >
</div>
I had facing the same problem, I really need to send a key from my jsp to java script, It spend around 4h or more of my day to solve it.
I include this tag on my JavaScript/JSP:
$scope.sucessMessage = function (){
var message = ($scope.messages.sucess).format($scope.portfolio.name,$scope.portfolio.id);
$scope.inforMessage = message;
alert(message);
}
String.prototype.format = function() {
var formatted = this;
for( var arg in arguments ) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
<!-- Messages definition -->
<input type="hidden" name="sucess" ng-init="messages.sucess='<fmt:message key='portfolio.create.sucessMessage' />'" >
<!-- Message showed affter insert -->
<div class="alert alert-info" ng-show="(inforMessage.length > 0)">
{{inforMessage}}
</div>
<!-- properties
portfolio.create.sucessMessage=Portf\u00f3lio {0} criado com sucesso! ID={1}. -->
The result was: Portfólio 1 criado com sucesso! ID=3.
Best Regards
Just in case someone still struggles with this, I had similar problem when trying to keep track of user session/userid on multipage form
Ive fixed that by adding
.when("/q2/:uid" in the routing:
.when("/q2/:uid", {
templateUrl: "partials/q2.html",
controller: 'formController',
paramExample: uid
})
And added this as a hidden field to pass params between webform pages
<< input type="hidden" required ng-model="formData.userid" ng-init="formData.userid=uid" />
Im new to Angular so not sure its the best possible solution but it seems to work ok for me now
Directly assign the value to model in data-ng-value
attribute. Since Angular interpreter doesn't recognize hidden fields as part of ngModel.
<input type="hidden" name="pfuserid" data-ng-value="newPortfolio.UserId = data.Id"/>
I use a classical javascript to set value to hidden input
$scope.SetPersonValue = function (PersonValue)
{
document.getElementById('TypeOfPerson').value = PersonValue;
if (PersonValue != 'person')
{
document.getElementById('Discount').checked = false;
$scope.isCollapsed = true;
}
else
{
$scope.isCollapsed = false;
}
}
Below Code will work for this IFF it in the same order as its mentionened make sure you order is type then name, ng-model ng-init, value. thats It.
Here I would like to share my working code :
<input type="text" name="someData" ng-model="data" ng-init="data=2" style="display: none;"/>
OR
<input type="hidden" name="someData" ng-model="data" ng-init="data=2"/>
OR
<input type="hidden" name="someData" ng-init="data=2"/>
참고URL : https://stackoverflow.com/questions/18446359/angularjs-does-not-send-hidden-field-value
'Programing' 카테고리의 다른 글
주어진 날짜의 정확한 주 번호를 얻으십시오 (0) | 2020.05.13 |
---|---|
Mac에 gitk 설치 (0) | 2020.05.13 |
'touchstart'및 'click'이벤트를 바인딩하지만 둘 다에 응답하지 않는 방법은 무엇입니까? (0) | 2020.05.13 |
Atom.io 편집기에서 html 형식을 지정하는 명령이 있습니까? (0) | 2020.05.13 |
일치하는 파일 만 표시하도록 grep 출력 (0) | 2020.05.13 |