how to create buttons in angularjs - angularjs

I am making a game that has 50 buttons and everybutton has an identity as a color and an id. On clicking every button there color changes to what it has been defined. If the user clicks on the 25th button , he wins. Only three tries for clicking. I am however unable to do the first step of creating buttons. Please help. I use angularjs1.
<html ng-app="Bluebox">
<head>
<title>BlueBox</title>
<script src="angular.js"></script>
</head>
<body>
<div ng-controller="BoxController">
<button type="button" value = "bluebox" >
<li ng-repeat="x in boxlength">
{{index+1}}
</li>
</button>
</div>
<script>
angular.module("Bluebox",[])
.controller("BoxController",["$scope",function($scope){
$scope.boxlength=50;
$scope.index=0;
}])
</script>
</body>
</html>

Your ng-repeat is not at the right place. You want to repeat buttons.
<button ng-repeat="..." type="button" value="bluebox"></button>
Then the format of ng-repeat is not correct. This directive doesn't repeat a number of times, it repeats in an array.
What we usually do is create a method that create an array based on a number:
<button ng-repeat="i in times(number)" type="button" value="bluebox"></button>
Get number could look like:
$scope.number = 5;
$scope.times= function(x) {
return new Array(num);
}
Since the array created has indentical "values" you need to track by $index
function Main($scope) {
$scope.number = 50;
$scope.times= function(x) {
return new Array(x);
}
}
angular.module('test', []);
angular.module('test')
.controller('Main', Main);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div ng-app="test">
<div ng-controller="Main">
<button ng-repeat="i in times(number) track by $index" type="button">{{$index}}</button>
</div>
</div>

Related

How to add text from textbox in angularjs1

I have written a code for adding messages to the page below the textbox. The text box has an add button . As soon i write a message in the textbx and click on add, the message should appear on the next line. I have used ng-repeat to repeat the process of adding messages whenever the add button is clicked. However i am getting error messages -
Expression 'addMessage()' is non-assignable.
And Error -
angular.js:13283 ReferenceError: message is not defined.
Please help me with the code.
<html ng-app="Swabhav.Message">
<head>
<title>message-app</title>
<script src="angular.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<div ng-controller="MessageAdd">
<h3>To Add Message:</h3>
<input text="text" ng-model="addMessage()">
<li ng-repeat="mess in message">
<button type="button" ng-click="addMessage()">Add</button>
</li>
<br>
<li><p> {{mess}}</li>
</p><br>
</div>
<script>
angular.module("Swabhav.Message", [])
.controller("MessageAdd", ["$scope", function($scope) {
$scope.message = [];
$scope.addMessage = function() {
$scope.message.push(message);
};
}]);
</script>
</body>
</html>
Try it:
HTML
<body>
<div ng-controller="MessageAdd">
<h3>To Add Message:</h3>
<input text="text" ng-model="messagetext">
<button type="button" ng-click="addMessage()">Add</button>
<li ng-repeat="mess in message">{{mess}}</li>
</div>
</body>
CONTROLLER:
angular.module("Swabhav.Message",[])
.controller("MessageAdd",["$scope",function($scope){
$scope.messagetext = "";
$scope.message=[];
$scope.addMessage =function(){
$scope.message.push($scope.messagetext);
$scope.messagetext = "";
}
}]);
You have some errors.
First, you can't assign a function to a model. You have to add te value on your model to the array of messages. Then your button has to be before the ng-repeat or you will have one botton for each element on the list and {{mess}} inside the ng-repeat.
<input text="text" ng-model="message">
<button type="button" ng-click="addMessage()">Add</button>
<ul>
<li ng-repeat="mess in messages">
{{mess}}
</li>
</ul>
In your controller I would rename the array to messages and assign a empty array to your model.
$scope.messages=[];
$scope.message = "";
$scope.addMessage =function(){
$scope.messages.push($scope.message);
$scope.message = "";
}
Try this code and tell me if it is what you are trying to do and if you understand the code
Jsfddle

ng-repeat limitTo automaticly trims limit and doesn't return it back

I have item array that changes in application.
When I delete items limitTo automatically trims its limit value, but when I add items it doesn't return the original limit value back. Like as limit=5 and items.length becomes 2 limitTo value becomes 3 and never grows back to 5 when items.length increases. Uplating limit doesn' work.
JS:
$scope.filterLimit = 5;
$scope.itemList2 = ['item1', 'item2', 'item3', 'item4']
HTML:
<div ng-repeat="i in itemList2 | limitTo: filterLimit">
<h5>{{i}}</h5>
</div>
<button ng-click="itemList2.push('new item')"> Add </button><br>
<button ng-click="itemList2.length = itemList2.length-1"> Delete </button><br>
<button ng-click="filterLimit = filterLimit+1"> Update </button>
Well, the main problem is that you're adding the same element to list, so ngRepeat claims about it giving the following error: ngRepeat:dupes.
To solve it, you must use track by expression in your ngRepeat, like this:
<div ng-repeat="i in itemList2 | limitTo: filterLimit track by $index">
Note: Filters, like limitTo, orderBy, etc... must come before track by expression.
Also I recommend you to use functions of controller for ng-click() instead of doing all in view.
Here's a version with all issues fixed:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.filterLimit = 5;
$scope.itemList2 = ['item1', 'item2', 'item3', 'item4'];
$scope.add = function() {
$scope.itemList2.push('item');
}
$scope.delete = function() {
$scope.itemList2.pop();
}
$scope.increment_filter = function() {
$scope.filterLimit++;
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div ng-repeat="i in itemList2 | limitTo: filterLimit">
<h5 ng-bind="i"></h5>
</div>
<button ng-click="add()"> Add </button>
<br>
<button ng-click="delete()"> Delete </button>
<br>
<button ng-click="increment_filter()"> Update </button>
<hr>
List: <pre ng-bind="itemList2"></pre>
Limit: <pre ng-bind="filterLimit"></pre>
</body>
</html>

AngularJS Get Filtered Scope onClick

I want to get an alert button for showing the filtered object of my filtered data in Angular.
In my HTML template i can get the object i want with: {{(portals|myFilter:or| filter:search )}}
I have my button :
<a ng-href='#here' ng-click='go()' >click me</a>
and my function go() is already working but now I need the object wich I can call with : {{(portals|myFilter:or| filter:search )}} in my go() function... Any idea?
I have already tried to write the object in the button but I didnt even believed that this is too easy. There must be a way to get the same object in my controller ?
<a ng-href='#here' ng-click='go(myFilter,search)' >click me</a>
You can assign filteredItems with the following syntax:
{{filteredItem = (portals|myFilter:or| filter:search )}}
<a ng-href='#here' ng-click='go(filteredItem)' >click me</a>
You can check the below snippet for an example.
angular.module("myApp", []).controller("myCtrl", function($scope) {
$scope.items = ["apple", "banana", "orange"];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input ng-model="query"/>
{{filteredItems = (items | filter:query)}}
<div>Filtered Items: {{filteredItems}}<div>
</div>
</body>
</html>

How to dynamically create text box when we click on a link using angularjs

I have a problem to show INPUT field when do some action.
I have BUTTON (Click here) as soon as user made a click event on button i wanted to show input field
I have done this by using jQuery.
Can any one help me in Angular.js
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.boxShow = false;
});
</script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
show box
<div ng-show="boxShow">
<textarea rows="4" cols="50">text</textarea>
</div>
</div>
</div>
https://jsfiddle.net/bxwjpmaa/1/
HTML
<div class="btn btn-primary" ng-click="openTextBox();">Click Me To open text box</div>
<div ng-show="openTextBox == true">
<input type="text"/>
</div>
SCRIPT :
$scope.openTextBox = function () {
$scope.openTextBox = true;
}
please don't take scope variables and function names same
example here
$scope.openTextBox = function () {
$scope.openTextBox = true;
}
//this is not correct as per angular documentation because scope.openTextBox name already assigned to scope function,again its assigning scope variable "$scope.openTextBox = true" here u will get errors when ever u clicked div second time" TypeError: boolean is not a function" it will throw this error.so please dont use which is already assigned scope function dont assign scope variable
see this fiddle url : https://jsfiddle.net/veerendrakumarfiddle/bxwjpmaa/2/
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ol>
<li ng-repeat="element in elements">
<input type="text" ng-model="element.value"/>
</li>
</ol>
<br/>
<b>Click here to add Textbox:</b><br/><input type="button" value="New Item" ng-click="newItem()"/>
<br/>
<br/>
<b>Click here to see ng-model value:</b><br/>
<input type="button" value="submit" ng-click="show(elements)">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var counter=0;
$scope.elements = [ {id:counter, value : ''} ];
$scope.newItem = function(){
counter++;
$scope.elements.push( { id:counter,value:''} );
}
$scope.show=function(elements)
{
alert(JSON.stringify(elements));
}
});
</script>
</body>
</html>

Generate dynamic form input fields and collect field data in an array

I am stuck with this little task.
I need to generate form input fields dynamically by clicking 'add' button on the form.
The form is supposed to create DB table schema. So every input field is a DB table field name.
I am OK generating the fields dynamically but have trouble with gathering the actual data.
<form ng-controller="NewTableCtrl" ng-submit="submitTable()">
<input type='text' ng-model='table.title' placeholder='Title:'>
<input ng-repeat="field in fields" type='text' ng-model='table.fields' placeholder='Field:'>
<div>
<button type='submit'>Submit</button>
<button ng-click="addFormField()">Add</button>
</div>
</form>
.. and the controller
.controller('NewTableCtrl', function($scope) {
$scope.fields = [];
$scope.table = {};
$scope.addFormField = function () {
$scope.fields.push({});
}
$scope.submitTable = function () {
console.log($scope.table);
}
});
Looks simple. When I click 'Add' button it generates the new input field but it does it with the same model object (obveously). And that's where my misunderstanding lies. I thought that if I declare $scope.fields = [];in the controller then repeating field data will just go into the array. But it just echoes the input in every repeating input field. I understand now that this is how it is supposed to be with two way binding.
The reason I thought like this is by the analogy with an ordinary form submission where the repeating input field names become an array in the URL encoded form data.
So how do I solve this? The server needs to get an array of fields like this: fields: [field1, field2 ...] Do I need to generate input fields with different scope variable for each field? How do I do this?
Is this more complex then I thought and it needs to be a directive? If yes, please, show me how to do this.
Thanks.
Right now you are iterating $scope.fields. When you are adding a new field you push an empty object into $scope.fields, but every input's ng-model points to $scope.table.fields (which is non-existing until first input writes to it - then it will hold a string variable).
For this simple use case you could try:
app.controller('NewTableCtrl', function($scope) {
$scope.table = { fields: [] };
$scope.addFormField = function() {
$scope.table.fields.push('');
}
$scope.submitTable = function() {
console.log($scope.table);
}
});
And:
<input ng-repeat="field in table.fields track by $index" type='text' ng-model='table.fields[$index]' placeholder='Field:'>
Demo: http://plnkr.co/edit/6iZSIBa9S1G95pIMBRBu?p=preview
Take a look at this
Working Demo
html
<body>
<div ng-app=''>
<div ng-controller="questionCtrl">
<div>
<ul>
<li ng-repeat="elemnt in questionelemnt">
<div>
<div id={{elemnt.id}} style="display:inline" >
<span ng-model="elemnt.question" ng-hide="editorEnabled" ng-click="editorEnabled=true">
{{elemnt.question}}
</span>
<div ng-show="editorEnabled">
<input ng-model="elemnt.question" ng-show="editorEnabled" >
<button href="#" ng-click="editorEnabled=false">Done editing</button>
</div>
</div>
<div style="display:inline">
<span>
<input type="text" ng-model="elemnt.answer" placeholder="Answer" required/>
</span>
</div>
<span ng-hide="elemnt.length == 1">
<button ng-click="questionelemnt.splice($index, 1)">Remove</button>
</span>
</div>
<hr/>
</li>
<li>
<button ng-click="addFormField($event)">Add</button>
</li>
</ul>
</div>
<div>
<button ng-click="showitems($event)">Submit</button>
</div>
<div id="displayitems" style="visibility:hidden;">
{{questionelemnt}}
</div>
</div>
</div>
</body>
script
function questionCtrl($scope) {
var counter = 0;
$scope.questionelemnt = [{
id: counter,
question: 'Question-Click on me to edit!',
answer: ''
}];
$scope.addFormField = function ($event) {
counter++;
$scope.questionelemnt.push({
id: counter,
question: 'Question-Click on me to edit!',
answer: ''
});
$event.preventDefault();
}
$scope.showitems = function ($event) {
$('#displayitems').css('visibility', 'none');
}
}
Variation of tasseKATTs solution using a hashmap instead of an array.
This allows me to have a nice JSON object I can just for-in over in order to build my query filter.
http://plnkr.co/edit/CArP3Lkmn7T5PEPdXgNt?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<style>
div{ margin: 1em;}
input{margin-left:1em;}
</style>
</head>
<body ng-controller="myCtrl">
<h2>Using a filter map tied to ng-model to create a filter object</h2>
<div ng-repeat="field in fields">
{{field}}<input ng-model=filters[field] />
</div>
<hr>
<h3>Filter</h3>
{{filters}}
<script>
var app=angular.module("app",[]);
app.controller("myCtrl",function($scope){
$scope.filters={};
$scope.fields=["name","address","phone","state"];
});
angular.bootstrap(document,["app"]);
</script>
</body>
</html>

Resources