I have a html file with 2 buttons outside the form. The idea is that when a button is clicked, the form will be shown and the form element “role_id” will be set to a passed value of 1 or 2. I cannot figure out the code to include inside the controller to set the value of role_id. Can you please help?
Index.html
<button class="btn btn-custom" ng-click="formToggle(1)" > Add Role 1</button>
<button class="btn btn-custom" ng-click="formToggle(2)"> Add Role 2</button>
<form class="form-horizontal" name="persForm" id="persForm" ng-submit="insertInfo(persInfo);" >
<input type="hidden" name="role_id" id="role_id" class="form-control" ng-model="persInfo.role_id" value="" />
</ form>
Controller.js
var crudApp = angular.module('crudApp',[]);
crudApp.controller("DbController",['$scope','$http', function($scope,$http){
$scope.formToggle = function(id){
$('#persForm').slideToggle();
//Code here to set form element ‘role_id’ to id
}
}]);
I’ve tried getElementById and other javascript DOM methods but it doesn’t seem to work inside AngularJS.
2
Answers
You’d better select the input by its name inside the form…
Don’t query all elements by IDs. So you can remove the id attribute from the input.
And for god’s sake please stop using
var
. Useconst/let
please.Even in AngularJS.
For AngularJS,
ng-model
corresponds to an object value in the$scope
. In your case, it corresponds topersInfo.role_id
. All you need to do is to set that property when the button is clicked. If you inspect the element you’ll see it’s value is set via theng-model
connection