Rendering Angularjs Template from within controller - angularjs

Suppose I have following angularjs template
<script type="text/ng-template" id="tmp">
<li>
{{firstname}} {{lastname}}</li>
</script>
and I have two textboxes and a save button like
<input name="firstname" type="text"/>
<input name="lastname" type="text"/>
<button name="save" text="save"/>
when user enters values in firstname and lastname textboxes and press on save button I want these two values to be passed to the template and resultant html should be appended to an existing ul. How can I do it with angular?

You could create a directive to dynamically compile your template and append it to the ul when someone hits the save button, but that's basically the whole purpose of ng-repeat.
Here's how it can work with an ng-repeat instead:
angular.module('main', []);
angular.module('main').controller('MainCtrl', function ($scope) {
$scope.names = [];
$scope.save = function () {
$scope.names.push({first: $scope.firstname, last: $scope.lastname});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="main" ng-controller='MainCtrl'>
<input name="firstname" type="text" ng-model='firstname'/>
<input name="lastname" type="text"ng-model='lastname'/>
<button name="save" text="save" ng-click='save()'>save</button>
<ul>
<li ng-repeat='name in names'>{{name.first}} {{name.last}}</li>
</ul>
</div>

Related

AngularJS v1.5.5 Reset form not working for invalid input fields

I have the code below (or see the fiddle) and I try to reset form and clear all input fields too for each form.
With AngularJS version 1.2.1 is working fine! but in my app I using version 1.5.5 because I have other libraries for separating the nested forms in <md-tab> tags using material framework who need this version.
The problem is when any field it's invalid then reset does not work as expected and these fields remain unchanged instead to be clear.
There is another way to clearing all fields (of nested form) when I click reset button ?
angular.module("main", [])
.controller("register", function($scope) {
$scope.data = {
A: {},
B: {}
};
$scope.reset = function(form) {
form.$setPristine();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body ng-app="main">
<div ng-controller="register" class="form">
<form name="form" novalidate role="form">
<div class="form">
<h1>TAB1 - Form A:</h1>
<ng-form name="A">
A1:
<input type="text" ng-model="data.A.A1" ng-minlength="4" ng-maxlength="15" />A2:
<input type="text" ng-model="data.A.A2" ng-minlength="4" ng-maxlength="15" />
<button type="button" ng-disabled="A.$pristine" ng-click="reset(A); data.A=null;">Reset</button>
<br/>
<strong>A.$pristine =</strong> {{A.$pristine}}
<strong>A.$valid =</strong> {{A.$valid}}
</ng-form>
</div>
<br/>
<br/>
<div class="form">
<h1>TAB2 - Form B:</h1>
<ng-form name="B">
B1:
<input type="text" ng-model="data.B.B1" ng-minlength="4" ng-maxlength="15" />B2
<input type="text" ng-model="data.B.B2" ng-minlength="4" ng-maxlength="15" />
<button type="button" ng-disabled="B.$pristine" ng-click="reset(B); data.B=null;">Reset</button>
<br/>
<strong>B.$pristine =</strong> {{B.$pristine}}
<strong>B.$valid =</strong> {{B.$valid}}
</ng-form>
</div>
</form>
<h1>data:</h1>
<pre>{{data | json}}</pre>
</div>
</body>
It's because ng-model binds to the A and B objects by reference in $scope.data. If you remove the $scope.data.A = null from your ng-click and reset the object without creating a new one, it works:
https://jsfiddle.net/utwf604r/15/
$scope.reset = function (form)
{
// don't change the reference to A
// $scope.data.A = {} wont work!!
angular.extend($scope.data, {A:{A1:'',A2:''}, B:{B1:'',B2:''}});
form.$setPristine();
};

Angular js Dynamic Input and show value

I want dynamic input in my form so that user can add many input as much he wants
Same time I want to display the value of it..
Example:
Suppose i have one input
Customer: <input type="text" ng-model="name"/> <!--first input>
<a>Add more</a>
I can easily get value for it
All customers <p ng-bind="name"></p>
BUT if users add one more customer name input, Then how can i show that value
Under "All customers tag"
All customers <p ng-bind="name"></p> // Customer1,Customer1 name here
Use an array of objects on scope in conjunction with a ng-repeat. The button will then add to the array.
View:
<p ng-repeat="item in array">Name: <input type="text" ng-model="item.name" ></p>
<button ng-click="add()">Add</button>
<p>All customers</p>
<p ng-repeat="item in array">{{item.name}}</p>
Js:
app.controller('MainCtrl', function($scope) {
$scope.array = [];
$scope.add = function () {
$scope.array.push({ name: ''});
}
$scope.add();
});
Plunkr
You have to create array.
In your controller
$scope.inputs = [];
$scope.add = function() {
$scope.inputs.push({value: ''});
}
$scope.add();
now in HTML
<div ng-repeat="input in inputs">
<input type="text" ng-model="input.value" />
</div>
<button ng-click="add()">Add</button>
This is raw concept of how that might be done.
Update
Added plunker example
http://plnkr.co/edit/bHLXCjsP46GiixysZZ83?p=preview

Uncheck checkbox with submit - AngularJS

I am trying to uncheck checkbox with submit button. The idea is when checkbox is checked button is shown, and when button is clicked checkbox is unchecked and button is hidden.
HTML page:
<html ng-app="myApp" ng-controller="myCtrl">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="script.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div ng-repeat="foo in boxes">
<div>
<input type="checkbox" name="cb" id="cb" ng-model="show" />{{foo}}
</div>
<div ng-show="show">
<form ng-submit="submit()">
<input type="submit" name="sumbit" id="sumbit" value="Hide" />
</form>
</div>
</div>
</body>
</html>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.boxes = ['a','b','c'];
$scope.submit = function(){
$scope.show = false;
}
});
On Plukner: http://plnkr.co/edit/z9W0w18dkgYJ3D5Q3aR2?p=preview
Thanks for any help!
The problem is that you're using a single variable to store states of 3 items yet Angular creates a scope for each context in the ng-repeat iteration. By changing show to an array and using $index to reference each of them, the show array from the main scope is passed to all three child scopes and there are no conflicts, so it works:
app.controller('myCtrl', function($scope) {
$scope.boxes = ['a','b','c'];
$scope.show = [];
$scope.submit = function(){
$scope.show = [];
}
});
HTML
<div ng-repeat="foo in boxes">
<div>
<input type="checkbox" name="cb" id="cb" ng-model="show[$index]" />{{foo}}
</div>
<div ng-show="show[$index]">
<form ng-submit="submit()">
<input type="submit" name="sumbit" id="sumbit" value="Hide" />
</form>
</div>
</div>
See it here: http://plnkr.co/edit/kfTMaLTXWtpt7N9JVHAQ?p=preview
(note sure if this is exactly what you wanted because there's no question, but it's enough to get you started)
UPDATE
And here is the version where Hide unchecks only "its own" checkbox ($scope.submit now accepts the index parameter): http://plnkr.co/edit/YVICOmQrPeCCUKP2tBBl?p=preview
You need to change the html code and simplify it as
Instead of form use simple ng-click
<div ng-show="show">
<input type="submit" value="Hide" ng-click="show = !show" />
</div>

AngularJS: How to trigger function call when a form field gets focus

I want my controller to perform some action when a user clicks in a form field (when the form field gets focus). How can I do this? See this plunker.
Here is my controller:
angular.module('myApp', [])
.controller('AppCtrl', ['$scope',
function($scope) {
$scope.field1 = "Default text";
$scope.focus = false;
$scope.formFieldJustGotFocus = function() {
$scope.focus = true;
// Do all the stuff I need to happen when the form has just gotten focus
}
}
]);
And here is the view:
<body ng-app="myApp" ng-controller="AppCtrl">
<h3>Testing</h3>
<p>I want to perform some action in the controller when a form field gets focus. How can I best achieve this?</p>
<form name="myForm">
<input type="text" name="field1" ng-model="field1">
</form>
<p>Form field has focus: {{focus}}</p>
</body>
You can use the ngFocus directive. The inverse is ngBlur.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<input type="text" ng-focus="isFocused = true" ng-blur="isFocused = false">
<p ng-if="isFocused">Focus !</p>
</div>
<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus()">
use like this ng-focus
Try ng-focus.
See more info:
https://docs.angularjs.org/api/ng/directive/ngFocus
use -> ng-focus
<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus();">
this plunker
in the code he had written the function formFieldJustGotFocus(), but it was not bound to the focus event

Bind dynamic element creation to keypress with AngularJS

I am trying to append an element to the DOM from user text input using AngularJS.
The desired behaviour is:
User types string into input ng-model "newTask"
Presses enter key
Dynamic element is then appended to the DOM
The relevant section of HTML is as follows:
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
<div class="task-list">
<a class="task"><span class="text">{{ newTask }}</span></a>
</div>
Currently the HTML is instantly updated. How can I bind this event to only happen after enter keypress? The AngularJS UI is also loaded.
Many appreciations,
an AngularJS newbie
Try creating a temp value
Html:
<input type="text" placeholder="Type then press enter to create task" ng-model="tmpTask" ng-keypress="saveTask($event)" />
Your ng-model binds to a tmpTask property. Only when enter is pressed, save it back to newTask
JS:
app.controller('MainCtrl', function($scope) {
$scope.saveTask = function (event){
if (event.keyCode == 13){
$scope.newTask = $scope.tmpTask;
}
}
});
DEMO
html
<form ng-submit="createTask()">
<input type="text" ng-model="newTaskText" />
</form>
<div ng-repeat="task in tasks">{{ task.text }}</div>
controller
$scope.tasks = [];
$scope.createTask = function() {
$scope.tasks.push({
text: $scope.newTaskText
});
};
Since one of the other answers addresses the ng-keypress, I'll offer up the fact you don't need to use the ng-keypress event but can just watch the variable instead which negates the need for enter:
http://plnkr.co/edit/osFGRtpHG46bMyp15mc8?p=preview
app.controller('MainCtrl', function($scope) {
$scope.taskList = [];
$scope.$watch('newTask', function(newVal){
if (newVal=="newTask") {
$scope.taskList.push("Task " + $scope.taskList.length);
$scope.newTask = null;
}
});
});
<body ng-controller="MainCtrl">
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
{{taskList.length}}
<div class="task-list" >
<a class="task" ng-repeat="task in taskList" ><span class="text">{{ task }} </span></a>
</div>
</body>

Resources