How set default value for dynamic input ng-repeat? - angularjs

I try to set default value for some input.
When i try in ionic framework to set a default value with
ng-value
that work but when i submit the form, i ll never get the default value. I get undefined.
I think it's because i cannot initiate my objet before render my form.
But with dynamic input name i can't find the way.
This is my controler :
function MyCtrl($scope) {
$scope.frequences = [];
$scope.medicaments = {
15:{dose : 10,frequence :"matin", name:"test1"},
16:{dose : 15,frequence :"matin", name:"test2"},
17:{dose : 19,frequence :"matin", name:"test3"},
};
$scope.genererDate = function(form) {
console.log($scope.frequences)
}
And my HTML
<ion-item ng-repeat="(key, value) in medicaments " >
<span class="">{{key}} - {{value.name}}</span>
<input type="text" ng-model="frequences[key]['dose']" ng-init="frequences.key['dose'] = value.dose" >
<input type="text" ng-model="frequences[key]['frequence']" ng-init="frequences[key]['frequence'] = value.frequence">
</ion-item>
i have a Fiddle, ng-value doesn't work here, so i have try with ng-init.
http://jsfiddle.net/hwunpm5q/2/

Use {} to define $scope.frequences = {}; not an array []
And it should be access through frequences[key]['dose'] not frequences.key['dose']
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.frequences = {};
$scope.medicaments = {
15:{dose : 10,frequence :"matin", name:"test1"},
16:{dose : 15,frequence :"matin", name:"test2"},
17:{dose : 19,frequence :"matin", name:"test3"},
};
$scope.genererDate = function(form) {
console.log($scope.frequences)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<form name="myform" novalidate="" ng-submit="genererDate(myForm)" >
<ion-item ng-repeat="(key, value) in medicaments " >
<span class="">{{key}} - {{value.name}}</span>
<input type="text" ng-model="frequences[key]['dose']" ng-init="frequences[key]['dose'] = value.dose" >
<input type="text" ng-model="frequences[key]['frequence']" ng-init="frequences[key]['frequence'] = value.frequence">
<br/>
</ion-item>
<br/>
<button class="button button-full buttonValiderTraitement" type="submit" ng-click="Submit">Submit</button>
</form>
</div>
</body>

Related

angularjs - Update ng-model value from controller?

View 1:
<div ng-controller="ctrl1">
<button ng-click="goToExtendedForm({'name':'aaa'})">
</button>
</div>
ctrl1:
$scope.selectedList = {
name: ""
};
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
$state.go('view2');
console.log(e); // prints updated value
};
View 2:
<div ng-controller="ctrl1">
<input
id="name"
name="name"
type="text"
ng-model="selectedList.name"
ng-readonly="true"
/>
</div>
But the input box is always empty, even though to get to the view the goToForm() is called. Why doesn't it update the HTML value?
Views are changed with ui.router's $state.
From your description, your code is supposed to work. Check if you are passing the right parameter into the function. Here is a working demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selectedList = {
name: ""
};
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
console.log(e); // prints updated value
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="goToForm({'name':'aaa'})">Change</button>
<br>
<input type="text" ng-model="selectedList.name" ng-readonly="true" />
</div>
Try adding $scope.$apply() at the end of your $scope.goToForm function
Try this ;
HTML Code
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<input
id="name"
name="name"
type="text"
ng-model="selectedList.name"
ng-readonly="true"
/>
<button ng-click="goToForm(testUserDetails)" >Go To</button>
</button>
</div>
</div>
Define controller like this;
function ClickToEditCtrl($scope) {
$scope.selectedList = {
name: ""
};
$scope.testUserDetails ={
name: "nimal"
}
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
console.log(e); // prints updated value
};
}

How to get selected option value from dropdown using angular

I have two drop downs with add resource button, when I click add resource button I need to pass selected option values from drop downs into insertResource method.How to get selected option value??I know we can easily do it using option:selected in jquery But I want do it in angular.Any help?
<body ng-app="intranet_App" ng-controller="myCtrl" ng-init="init()">
<div class="container">
<div class="row">
<div>
<label class="displayBlock margin">Project Name</label>
<input type="text" name="name" class="currentProjectName">
</div>
<div>
<label class="displayBlock margin">Resource Name</label>
<select name="ResourceInsert" id="allocateResource"><option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option></select>
</div>
<div>
<label class="displayBlock margin">Role Name</label>
<select name="ResourceInsert" id="allocateRole"><option data-ng-repeat="data in roleList" value="{{data.RoleId}}">{{data.RoleName}}</option></select>
</div>
</div>
<div class="row">
<button class="btn btn-primary addResource" ng-click="insertResource()">Add Resource</button>
</div>
</div>
</body>
<script>
var app = angular
.module('intranet_App', [])
.controller('myCtrl', function ($scope,$http) {
$scope.init = function () {
$scope.getProjId();
$scope.ResourceJson();
$scope.RoleJson();
}
$scope.getProjId = function () {
var url = document.URL;
var id = decodeURI(/id=([^&]+)/.exec(url)[1]);
var projectName = decodeURI(/val=([^&]+)/.exec(url)[1]);
$('.currentProjectName').val(projectName)
}
$scope.ResourceJson = function () {
$http.post('/Project/empList').then(function (response) {
$scope.resourceList = response.data;
console.log($scope.resourceList)
})
}
$scope.RoleJson = function () {
$http.post('/Project/roleList').then(function (response) {
$scope.roleList = response.data;
console.log($scope.roleList)
})
}
$scope.insertResource = function () {
}
});
</script>
If your questions is getting data of selected item of select. It is done as follows using ng-model directive:
<select name="ResourceInsert" id="allocateResource" ng-model="selectedValue">
<option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option>
</select>
In Controller:
console.log($scope.selectedValue, "selected Value"); //Your selected value which is EmpId.

Get the value of dynamic check boxes in angular js when submitting the form

In my HTML form there are 5 check boxes. How can I check which check boxes are checked or not at the time of the form submission?
I am using this little piece of code. Feel free to take it.
In your controller:
$scope.sentinel = [];
$scope.toggleSelection = function(value) {
// Bit trick, equivalent to "contains"
if (~$scope.sentinel.indexOf(value)) {
var idx = $scope.sentinel.indexOf(value);
$scope.sentinel.splice(idx, 1);
return;
}
$scope.sentinel.push(value);
};
Then in your HTML:
<span ng-repeat="key in $scope.yourarray">
<md-checkbox style="margin-left:30px;" aria-label="Select item"
ng-click="toggleSelection(key)"><span>{{ key }}</span></md-checkbox>
<br/>
</span>
This allows you to have an array of any size and using the sentinel array to register already checked values. If you check again a box, the toogleSelection will prevent you from adding again a value.
You can use the Checklist-model of Angular.js. It is very useful:
var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkAll = function() {
$scope.user.roles = angular.copy($scope.roles);
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
};
$scope.showCheckedOnes = function() {
var checkedBoxes = "";
for (var i = 0; i < $scope.user.roles.length; i++) {
checkedBoxes += $scope.user.roles[i] + " ";
}
alert(checkedBoxes);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://vitalets.github.io/checklist-model/checklist-model.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl1">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
</label>
<div>
<div>
<button ng-click="checkAll()" style="margin-right: 10px">Check all</button>
<button ng-click="uncheckAll()" style="margin-right: 10px">Uncheck all</button>
<button ng-click="checkFirst()" style="margin-right: 10px">Check first</button>
<button ng-click="showCheckedOnes()" style="margin-right: 10px">Show checked ones</button>
You can define the array value and map to html.
$scope.checkbox = [];
HTML
<input ng-model="checkbox[0] type="checkbox" />
<input ng-model="checkbox[1] type="checkbox" />
<input ng-model="checkbox[2] type="checkbox" />
<input ng-model="checkbox[4] type="checkbox" />
Or you can define checkbox as object and change checkbox[index] to checkbox[name].

validate dynamic form before submitting angular

I'm dynamically creating forms with ng-repeat and they have some validation attributes (simplified version):
<div class="row" ng-repeat="defect in model.defects">
<form name="form_{{defect.id}}" novalidate>
<input ng-model="defect.name" required/>
<input type="submit" ng-click="saveDefect(defect)"/>
</form>
</div>
Basically what I want to do is this:
$scope.saveDefect = function (defect) {
if ($scope.<how to get the form name here>.$invalid) {
return;
}
}
Since the form name has been created dynamically with an id how do I access it? Other ways of doing the same are also welcome ofcourse :)
You can use the bracket notation to access it :
$scope["form_"+defect.id]
What I advise you to do is :
var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
$scope.forms = {};
$scope.list = [{id: 1}, {id: 2}];
$scope.save = function(item) {
if ($scope.forms["form_" + item.id].$invalid) {
alert("error on form_" + item.id);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="App" ng-controller="Ctrl">
<div class="row" ng-repeat="item in list">
<form name="forms.form_{{item.id}}" novalidate>
<input ng-model="item.name" required/>
<input type="submit" ng-click="save(item)" />
</form>
</div>
</body>

Angular hide an element on blur

I got two elements paragraph and input tag. When i click the paragraph, the input should show and paragraph should hide. when the input is blurred the input should hide and paragraph should show.
I tried this but not working
<p ng-click="edit = true" ng-show="!edit">some text</p>
<div ng-show="edit" ng-blur="edit = false">
<input type=text name="email" ng-blur="blurUpdate()" />
</div>
Move ng-blur to input please see demo below
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope, $timeout) {
$scope.showEditor = function() {
$scope.edit = true;
var textbox = document.getElementById("input_email");
var tmp = $scope.text
$scope.text = ""
$timeout(function() {
textbox.focus();
$scope.text = tmp;
});
}
$scope.blurUpdate = function() {
// add this line
$scope.edit = false;
//your code
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl" ng-init="text='some text'">
<p ng-click="showEditor()" ng-show="!edit">{{text}}</p>
<div ng-show="edit">
<input type=text name="email" ng-blur="blurUpdate()" ng-model="text" id="input_email" />
</div>
</div>
</div>
the ngBlur is compatible with input tag, that is why it is not working:
<p ng-click="edit = true" ng-show="!edit">some text</p>
<div ng-show="edit" >
<input type=text ng-blur="edit = false" name="email" />
</div>
http://jsfiddle.net/xgp2qsww/1/

Resources