Sorry for dump, question, I am new to AngularJS and to JavaScript. I would like to iterate over collection by clicking the button.
<body ng-init="customers = [
{'name':'John', 'city':'Doe'},
{'name':'Anna', 'city':'Smith'},
{'name':'Peter', 'city':'Jones'}
]">
<div class="container" ng-app="myApp" ng-controller="myCtrl" >
<div class="span12">
<h1>{{name}}</h1>
<br/>
<p>{{city}}</p>
<button type="button" name="button" value="Next" ng-click="makeIterator($scope.customers)"></button>
</div>
</div>
So after clicking Next button I would like to see next iteration of customers displayed. How could I make it?
You can store an index and increment it when clicking on the button
<body ng-app="myApp">
<div class="container" ng-controller="myCtrl" >
<div class="span12">
<h1>{{customers[currentCustomerIdx].name}}</h1>
<br/>
<p>{{customers[currentCustomerIdx].city}}</p>
<button type="button" name="button" value="Next"
ng-click="index = (index + 1) % customers.length"></button>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.customers = [
{'name':'John', 'city':'Doe'},
{'name':'Anna', 'city':'Smith'},
{'name':'Peter', 'city':'Jones'}];
$scope.currentCustomerIdx = 0;
});
</script>
PFB the approach to do it:
<body>
<div class="container" ng-app="myApp" ng-controller="myCtrl">
<div class="span12">
<h1>{{customers[counter].name}}</h1>
<br/>
<p>{{customers[counter].city}}</p>
<button type="button" name="button" value="Next" ng-click="iterate();">NEXT</button>
</div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
$scope.customers = [
{'name':'John', 'city':'Doe'},
{'name':'Anna', 'city':'Smith'},
{'name':'Peter', 'city':'Jones'}
]
$scope.counter=0;
$scope.maxCount = $scope.customers.length - 1;
$scope.iterate = function(){
if($scope.counter == $scope.maxCount)
{
$scope.counter=0;
}
else{
$scope.counter++;
}
}
});
</script>
</body>
You can store an index on the controller's scope to iterate over the customers array by binding a click event on a button and use the index to retrieve a customer from the customers array.
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.index = 0;
vm.customers = customers;
vm.customer = vm.customers[vm.index];
vm.nextCustomer = nextCustomer;
function nextCustomer() {
vm.index = vm.index + 1;
if (vm.index === vm.customers.length) {
vm.index = 0;
}
vm.customer = vm.customers[vm.index];
}
}
var customers = [
{ name: 'Name 1', city: 'City 1' },
{ name: 'Name 2', city: 'City 2' },
{ name: 'Name 3', city: 'City 3' },
];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<div>
<span>Customer: </span>{{ctrl.customer.name}}
</div>
<div>
<span>City: </span>{{ctrl.customer.city}}
</div>
<button type="button" ng-click="ctrl.nextCustomer()">Next</button>
</div>
</div>
Related
Here is my todo.js file
//let example = angular.module("example", ["ngStorage"]);
example.controller("ExampleController", function($scope, $localStorage) {
$scope.save = function() {
let testObject = [
{
name:"aaa",
lastName:"bbb"
},
{
name:"ccc",
lastName:"ddd"
}
]
let myVal = $localStorage.myKey;
$localStorage.$reset();
if(!myVal){
console.log("okey");
$localStorage.myKey = testObject;
} else {
myVal.push({
name:"fff",
lastName:"ggg"
})
$localStorage.myKey = myVal;
}
$scope.datas = $localStorage.myKey;
}
$scope.load = function() {
console.log($localStorage.myKey)
}
});*/
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", function ($scope, $modal, $log) {
$scope.showForm = function () {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function () {
return $scope.userForm;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, userForm) {
$scope.form = {}
$scope.submitForm = function () {
if ($scope.form.userForm.$valid) {
console.log('user form is in scope');
$modalInstance.close('closed');
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
And here is my index.html file:
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="../node_modules/angular-1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>
<script src="./todo.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.9.0.js"></script>
</head>
<body>
<!--<div ng-app="example">
<div ng-controller="ExampleController">
<button ng-click="save()">Save</button>
<button ng-click="load()">Load</button>
<br>
<input type='text' ng-model='searchText' placeholder="Search..." />
<ul>
<li ng-repeat="data in datas | filter:searchText">
{{data.name}}
</li>
</ul>
</div>
</div>-->
<div ng-app="modalFormApp">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- PAGE HEADER -->
<div class="page-header">
<h1>AngularJS Form Validation</h1>
</div>
<div ng-controller="modalAccountFormController">
<div class="page-body">
<button class="btn btn-primary" ng-click="showForm()">Create Account</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Lastly here is my modal.html:
<div class="modal-header">
<h3>Create A New Account!</h3>
</div>
<form name="form.userForm" ng-submit="submitForm()" novalidate>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="name" required>
<p ng-show="form.userForm.name.$invalid && !form.userForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
<p ng-show="form.userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="form.userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="email" required>
<p ng-show="form.userForm.email.$invalid && !form.userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="form.userForm.$invalid">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</form>
I'm trying to open a modal when i click the button. I made comment line the other part which i'm using but it works fine. The second part is for only the modal but it is not working. I even can not open the modal. If there is a basic way to do this can you share with me? I only need to open this modal. I can handle the rest of it.
From the Docs:
There are a few things to keep in mind when using ngApp:
only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.
For more information, see
AngularJS ng-app Directive API Reference
Everything is in the title...
I can't get this to work:
(function(angular) {
'use strict';
angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.init = function() {
$scope.response = "press the button";
}();
$scope.data = {
availableOptions: [{
id: '1',
name: 'num'
}],
selectedOption: {
name: 'selected field'
}
};
$scope.data2 = {
availableOptions2: [{
id: '0',
name: 'null'
}
],
selectedOption2: {
name: 'null'
}
};
$scope.search = function() {
$scope.response = "you pressed a button \\o/";
alert($scope.response);
};
$scope.request = function(req) {
$http(req).then(function() { /*successCallback*/ },
function() { /*errorCallback*/ });
};
}]);
})(window.angular);
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="//code.angularjs.org/1.7.3/angular.min.js"></script>
<script src="analyzer.js"></script>
</head>
<body ng-app="app">
<div ng-controller="ctrl" ng-show="true">
<!--class="ng-hide" is automatically added when ng-show="false"-->
<!--SEARCH-->
<form name="myForm">
<label for="mySelect">Select a field:</label>
<select name="mySelect" id="mySelect" ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption"></select>
<br/>
<div style="color:#757575">
<input ng-model="query" type="text" size=45 class="form-control" placeholder="Search your {{data.selectedOption.name}} here..." />
<div ng-show="true">
or directly select your choice here...
<select name="subSelect" id="subSelect" ng-options="option.name for option in data2.availableOptions2
track by option.id" ng-model="data2.selectedOption2"></select>
<br/>
<button style="color:#757575" ng-click="search()">
...and go!</button>
</div>
</div>
</form>
<!--RESPONSE-->
<div ng-controller="ctrl" ng-show="true">
<p>{{response}}</p>
</div>
</div>
</body>
</html>
We can see that, even in this snippet, the view is not updated when I change the value of $scope.response... and alert($scope.response) shows that the button is okay... The use of things like $interval, $timeout, $apply, $watch did not solve the problem. Any ideas?
Thanks for your time.
And sorry if it was a dupe ; I just couldn't find the solution.
You are re instantiating the controller again which will re create the controller, in that case response is undefined, remove
<div ng-controller="ctrl" ng-show="true"> //remove ng-controller
<p>{{response}}</p>
</div>
Working snippet :
(function(angular) {
'use strict';
angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.init = function() {
$scope.response = "press the button";
}();
$scope.data = {
availableOptions: [{
id: '1',
name: 'num'
}],
selectedOption: {
name: 'selected field'
}
};
$scope.data2 = {
availableOptions2: [{
id: '0',
name: 'null'
}
],
selectedOption2: {
name: 'null'
}
};
$scope.search = function() {
$scope.response = "you pressed a button \\o/";
alert($scope.response);
};
$scope.request = function(req) {
$http(req).then(function() { /*successCallback*/ },
function() { /*errorCallback*/ });
};
}]);
})(window.angular);
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="//code.angularjs.org/1.7.3/angular.min.js"></script>
<script src="analyzer.js"></script>
</head>
<body ng-app="app" ng-controller="ctrl" >
<div ng-show="true">
<!--class="ng-hide" is automatically added when ng-show="false"-->
<!--SEARCH-->
<form name="myForm">
<label for="mySelect">Select a field:</label>
<select name="mySelect" id="mySelect" ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption"></select>
<br/>
<div style="color:#757575">
<input ng-model="query" type="text" size=45 class="form-control" placeholder="Search your {{data.selectedOption.name}} here..." />
<div ng-show="true">
or directly select your choice here...
<select name="subSelect" id="subSelect" ng-options="option.name for option in data2.availableOptions2
track by option.id" ng-model="data2.selectedOption2"></select>
<br/>
<button style="color:#757575" ng-click="search()">
...and go!</button>
</div>
</div>
</form>
<!--RESPONSE-->
<div ng-show="true">
<p>{{response}}</p>
</div>
</div>
</body>
</html>
I have list array.Inside that I have one nested array called types.I am trying to show types.work inside an input field with comma separated.
This is what I have tried:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="list.name">
<label ng-repeat="data in list.types">{{data.work}}{{$last ? '' : ', '}}</label>
</div>
</div>
Can anyone tell me that how to use ng-repeat values in single input?.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
$scope.input_model_value = ''
var temp = []
$scope.list.forEach(function(t1){
t1.types.forEach(function(val){
temp.push(val.work)
})
})
$scope.input_model_value = temp.join(',')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="input_model_value">
<label ng-repeat="data in list.types">{{data.work}}</label>
</div>
</div>
use multiple ng-repeat to access the nested array.
<label ng-repeat="data in list">
<label ng-repeat="d in data.types">
{{d.work}}
</label>
</label>
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
$scope.name = $scope.list[0].types.map((o) => o.work)
$scope.name = $scope.name.join(",")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="name">
<label ng-repeat="data in list">
<label ng-repeat="d in data.types">
{{d.work}}
</label>
</label>
</div>
</div>
In case You want some other solution. You can iterate over your array in JS file and assign the value to your input model.
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<body>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="listData">
</div>
</div>
</body>
<script>var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
$scope.listData = "";
for(var i=0;i<$scope.list[0].types.length;i++){
if($scope.listData!= undefined){
$scope.listData = $scope.listData+","+$scope.list[0].types[i].work;
}
}
}
});
</script>
</html>
You added the list an array so you can use ng-repeat in ng-repeat or you can directly use array first object like this
<input type="text" ng-model="list[0].name">
<label ng-repeat="data in list[0].types">{{data.work}}{{$last ? '' : ', '}}</label>
I'm a beginner of AngularJS, and I cannot solve the problem of the title. If we push the button changeText in the following code, the text of the textarea will change. But this event doesn't happen if we push the button changeTextNew which is added by pushing another button addNewButton`.
html
<div ng-app="app" ng-controller="MainCtrl">
<input name="widget.title" ng-model="widget.title"><br>
<input type="button" ng-click="setText()" value="changeText"><br>
<input type="button" id="piyo" value="addNewButton">
<div id="fuga"></div>
</div>
js
angular.module('app', [])
.controller('MainCtrl', function($scope) {
$scope.widget = { title: 'before' };
$scope.setText = function() {
this.widget.title = "after"
}
});
$(document).on('click', '#piyo', function() {
$('#fuga').append("<input type='button' ng-click='setText()' value='changeTextNew'><br>")
})
https://jsfiddle.net/sn512/guqjatt6/
Try to avoid using jQuery together with AngularJS.
Try this:
angular.module('app', [])
.controller('MainCtrl', function($scope, $compile) {
$scope.widget = { title: 'before' };
$scope.setText = function() {
this.widget.title = "after"
}
$(document).on('click', '#piyo', function() {
$("#fuga").append($compile("<input type='button' ng-click='setText()' value='changeTextNew'><br>")($scope));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
<input name="widget.title" ng-model="widget.title"><br>
<input type="button" ng-click="setText()" value="changeText"><br>
<input type="button" id="piyo" value="addNewButton">
<div id="fuga"></div>
</div>
I have a controller set up which contains a few functions to do form validation. In this controllers $scope I have an array $scope.errorMsgs that is populated with strings of error messages the user makes when filling out the form.
I also have a directive that displays this form. They are both attached to the same module. The controller and directive are in separate files within the same directory. However the scope in the directive's link function does not reference the $scope in the controller. They have different $ids in fact. Any ideas as to why this is happening?
Module:
angular.module('aop.availabilitysolver', [
'aop.services',
'checklist-model'
]).run(['widgetService', function(widgetService) { 'use strict';
widgetService.registerWidgets([
{
title: 'AVAILABILITYSOLVER.WIDGETS.AVAILABILITYSOLVER',
translatableDescription: 'AVAILABILITYSOLVER.WIDGETS.AVAILABILITYSOLVER',
type: 'aop-availability-solver',
configuration: {},
width: 1
}
]);
}]);
Controller
angular.module('aop.availabilitysolver')
.controller('AvailabilitySolverController', ['$scope',
function ($scope) { 'use strict';
//console.log($scope);
$scope.selectGoalDropdown = ['Impressions', 'Spend'];
$scope.selectGoalTimespan = ['Day', 'Week', 'Month'];
$scope.selectGoals = [
{
id: '1',
name: 'Impressions'
},
{
id: '2',
name: 'Spend'
}
];
$scope.selectTimespan = [
{
id: '4',
name: 'Day'
},
{
id: '5',
name: 'Week'
},
{
id: '6',
name: 'Month'
}
];
$scope.selectedItem = 'test2';
$scope.selectedItem1 = 'test3';
$scope.per = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20];
$scope.hours = [1, 3, 4, 12, 24, 36, 48, 72, 120, 168];
$scope.uncpd = ['uncapped'];
$scope.times = {
amt: [],
freq: [],
uncapped: []
};
$scope.caps = [];
$scope.quantity;
$scope.level = 'Fcap';
$scope.showErrors = false;
$scope.errorMsgs = [];
$scope.calculateFreqCaps = function(amt, freq, uncap) {
var rtn = [];
function isNothingSelected() { // No selections made
if(amt.length === 0 && freq.length === 0 && uncap.length === 0) {
rtn.push('Please choose frequency settings or select \'uncapped.\'');
$scope.errorMsgs.push('Please choose frequency settings or select \'uncapped.\'');
}
}
function malformedFrequencyOpts() { // Selected amount but no frequency & vice versa
if((amt.length > 0 && freq.length === 0) || (amt.length === 0 && freq.length > 0)) {
rtn.push('Please select both an amount and a frequency.');
$scope.errorMsgs.push('Please select both an amount and a frequency.');
}
}
function selectedTooMuch() { // Uncapped and frequency settings selected
if((amt.length > 0 || freq.length > 0) && uncap.length === 1) {
rtn.push('Choose uncapped only if no amount or frequency is selected');
$scope.errorMsgs.push('Choose uncapped only if no amount or frequency is selected');
}
}
isNothingSelected();
malformedFrequencyOpts();
selectedTooMuch();
if(rtn.length > 0) {
return rtn;
} else if (amt.length === 0 && freq.length === 0 && uncap.length === 1) { // Only uncapped selected
return ['uncapped'];
}
angular.forEach(amt, function (a) {
angular.forEach(freq, function (f) {
rtn.push(a + '/' + f + 'h');
});
});
return rtn;
};
$scope.validateSelectGoalQuantity = function(n) {
if(!Number(n)) {
$scope.errorMsgs.push('Quantity must be a number');
return false;
}
return true;
};
$scope.submitBtnClick = function() {
// Build Frequency cap JSON object
$scope.caps = $scope.calculateFreqCaps($scope.times.amt, $scope.times.freq, $scope.times.uncapped);
$scope.validateSelectGoalQuantity($scope.quantity);
if($scope.errorMsgs.length > 0) {
console.log($scope.errorMsgs);
// Show error message div and clear $scope.errorMsgs
$scope.showErrors = true;
//$scope.errorMsgs.length = 0;
}
else {
$scope.showErrors = false;
}
};
}]);
Directive
angular.module('aop.availabilitysolver')
.directive('aopAvailabilitySolver', ['$filter', function($filter) { 'use strict';
return {
restrict: 'E',
link: function(scope, element, attrs) {
angular.noop(attrs);
// Hide error div initially
$('.availabilitySolverErrorDisplay').hide();
var i = element.find('.levelRadio :radio');
i.on('click', function() {
if($(i[0]).prop('checked')) {
scope.level = 'Fcap';
element.find('.freqCapDiv').show();
}
else {
scope.level = 'Bid';
element.find('.freqCapDiv').hide();
}
});
console.log(scope);
},
templateUrl: 'features/availabilitySolver/availabilitySolver.html'
};
}]);
HTML
<div ng-controller="AvailabilitySolverController">
<div class="container-fluid availabilitySolverScreen1">
<div class="row">
<div class="alert alert-danger availabilitySolverErrorDisplay">
</div>
</div>
<div class="row">
Campaign Selector
</div>
<!-- Goals -->
<div class="row">
<h5>Select Goal</h5>
<form name="selectGoalForm" novalidate>
<div class="col-md-4">
<button name="goals" class="btn btn-default" ng-model="selectedItem" ng-options="value.id as value.name for (key, value) in selectGoals" data-style="btn-primary" bs-select></button>
</div>
<div class="col-md-4">
<div class="col-md-10">
<input type="number" name="quantity" class="form-control" placeholder="Quantity" ng-model="quantity">
</div>
<div class="col-md-2">
per
</div>
</div>
<div class="col-md-4">
<button name="timespan" class="btn btn-default" ng-model="selectedItem1" ng-options="value.id as value.name for (key, value) in selectTimespan" data-style="btn-primary" bs-select></button>
</div>
</form>
</div><!-- End goals -->
<!-- Level cap -->
<div class="row">
<h5>Level</h5>
<div class="col-md-12">
<form class="levelRadio">
<input name="level" value="Fcap" type="radio" checked> Fcap
<input name="level" value="Bid" type="radio"> Bid
</form>
</div>
</div><!-- end level cap -->
<!-- Frequency cap analysis -->
<div class="row freqCapDiv">
<h5>Customize Frequency Cap for Analysis</h5>
<div class="col-md-8">
<!-- per -->
<div class="col-md-4">
<ul>
<li ng-repeat="item in per">
<input type="checkbox"
checklist-value="item"
checklist-model="times.amt" /> {{item}} per
</li>
</ul>
</div><!-- end per -->
<!-- hour(s) -->
<div class="col-md-4">
<ul>
<li ng-repeat="item in hours">
<input type="checkbox"
checklist-value="item"
checklist-model="times.freq" /> {{item}} hr
</li>
</ul>
</div>
<!-- uncapped -->
<div class="col-md-4">
<ul>
<li ng-repeat="item in uncpd">
<input type="checkbox"
checklist-value="item"
checklist-model="times.uncapped" /> uncapped
</ul>
</div>
</div>
<div class="col-md-4">
</div>
</div><!-- end frequency cap analysis -->
<!-- submit button -->
<div class="row">
<button class="btn btn-primary" ng-click="submitBtnClick()">Submit</button>
</div>
</div>
</div>