Generate HTML dynamically on button click in Angular js - javascript

I have a select box. I want to generate the same on a 'Add New' button click.
View
<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="Get_toolNames()">Add New
<i class="fa fa-plus"></i>
</button>
<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name" ng-options="t.tm_id as t.tm_name for t in tools" required>
<option value="">Select</option>
</select>
How can I generate the same on this button click?

If you have
<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="buttonClick"> Add New
<i class="fa fa-plus"></i>
</button>
In your controller you can inject and use $compile service.
$scope.buttonClick = function(){
var el = angular.element(/* Here your element */);
el.append( '<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name" ng-options="t.tm_id as t.tm_name for t in tools" required>' +
'<option value="">Select</option>' + '</select>')
$compile(el)($scope);
}
Change your logic to get the data and the element you want:
For more see $compile.
Update
var sample_2_tbody = angular.element('#sample_2 tbody');
$compile(sample_2_tbody)($scope);
How to inject a service in the controller:
app.controller('MyController', ['$scope', '$compile', function($scope, $compile){
}])

In AngularJS views are just a model reflection and their scope is only for data presentation. That's mean you never need to manually copy a DOM Element, you just need to operate on the bound model.
function TestCtrl($scope, select) {
copy = () => angular.copy(select);
$scope.selects = [copy()];
$scope.values = {};
$scope.add = () => {
//$scope.selects.unshift(select); // add at the beginning
$scope.selects.push(copy()); // add at the end
};
}
angular
.module('test', [])
.value('select', [{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
subItem: { name: 'bSubItem' }
}])
.controller('TestCtrl', ['$scope', 'select', TestCtrl])
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<button ng-click="add($event)">Add</button>
<hr>
<div ng-repeat="select in selects track by $index">
<select ng-model="values[$index]" ng-options="t as t.label for t in select">
</select>
</div>
<hr>
<pre><code ng-bind="values | json"></code></pre>
</article>
</section>

Related

AngularJS filter infinite loop

I've written a filter in AngularJS, which was working fine when using it with ng-options on an input select.
Since I needed a more powerful select box with additional functionality, I've written a directive.
The directive has an isolated scope with the filtered options being passed via a two-way binding. Unfortunately, my filter produces a "10 $digest() iterations reached"-error.
This is my filter:
angularAMD.filter('gasUsableInSpacer', function(){
return function(gasTypes, isSealed) {
var filtered = [];
angular.forEach(gasTypes, function(gasType){
if(isSealed){
if(gasType.usableInSealedSpacer)
filtered.push(gasType);
}
if(!isSealed){
if(gasType.usableInSecondarySpacer)
filtered.push(gasType);
}
});
return filtered;
};
});
and this is how I included my directive:
<filter-select options="allGasTypes | gasUsableInSpacer:element.sealed" element="element.gasType" id="gasTypeX"></filter-select>
The above way isn't working, while this is working fine:
<select class="form-control" ng-model="element.gasType" ng-options="gasType as gasType.naturalName for gasType in allGasTypes | gasUsableInSpacer:element.sealed track by gasType.id" name="gasTypeX" id="gasTypeX">
</select>
This is my directives controller:
angularAMD.directive("filterSelect", function (angularLoad) {
return {
templateUrl: 'rmlModMainApp/directives/filterSelect.html',
restrict: 'E',
scope: {
options : '=',
element: '='
},
link: function(scope, element, attr) {
angularLoad.loadCSS(requirejs.toUrl('rmlModMainApp/directives/filterSelect.css'));
scope.listVisible = false;
scope.selectOption = function(option){
scope.element = option;
scope.toggleList();
};
scope.toggleList = function(){
scope.listVisible = !scope.listVisible;
}
}
}
});
});
And the part of the view that is supposed to render the options:
<div class="filterSelect">
<div class="filterSelectContent" ng-show="listVisible">
<form class="filterSelectSearch">
<div class="input-group col-xs-12">
<input type="text" class="form-control" id="filterText" ng-model="search.text" placeholder="filter" ng-model-options="{debounce: {'default':500, 'blur':0}}">
<span class="input-group-addon"><i class="fa fa-lg fa-filter"></i></span>
</div>
</form>
<div class="filterSelectList">
<ul>
<li ng-repeat="option in options track by option.id" ng-click="selectOption(option)">{{option.x}} <span ng-if="option.y">({{option.y}}mm)</span> [{{option.z}}] </li>
</ul>
</div>
</div>
</div>
I have no idea what I'm doing wrong.

Angular JS collect all input values from a div

I am new to Angular JS, I created a div with input elements and I didn't use ng-model for input boxes.
<div class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat=" x in $ctrl.outputProductAttributeValueList">
{{x}} <input type="text" />
</p>
<br>
<button type="submit" ng-click="$ctrl.onRankingFormSubmit()"> SUBMIT</button>
</div>
</div>
When I click on submit button I have to access all input values .Please help me how to do that .. I tried as below.
angular.module("productList")
.component("productList",{
templateUrl : "product-list/product-list.template.html",
controller : ["$http" ,"$scope","$document",function productListController($http,$scope,$document){
var self = this;
self.outputProductAttributeValueList =[ "age", "gender","all"];
self.onRankingFormSubmit = function () {
var queryResult = $document[0].getElementById("rankingForm")
console.log(queryResult);
// HERE queryResult is printing how to proceed further
};
}]
});
Now I want to collect all those input values dynamically created by ng-repeat. Please tell me how to do that ?
AngularJS ngModel is the standard approach for binding the view into the model instead of interacting directly with the DOM.
You can get all the inputs within the div id="rankingForm" you can do:
var inputs = $document[0]
.getElementById('rankingForm')
.getElementsByTagName('input');
Or by using Document.querySelectorAll():
var inputs = $document[0].querySelectorAll('#rankingForm input');
Once you have the inputs than iterate over all of them to get the values.. Notice that I have added attribute name to the inputs:
Code whitout ngModel:
angular
.module('App', [])
.controller('AppController', ['$scope', '$document', function ($scope, $document) {
$scope.outputProductAttributeValueList = ['age', 'gender', 'all'];
$scope.onRankingFormSubmit = function () {
var inputs = $document[0].querySelectorAll('#rankingForm input');
inputs.forEach(function(input) {
console.log(input.name + ': ' + input.value);
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController" class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat="x in outputProductAttributeValueList">
{{x}} <input type="text" name="{{x}}" />
</p>
<br>
<button type="submit" ng-click="onRankingFormSubmit()">SUBMIT</button>
</div>
</div>
Code with ngModel:
angular
.module('App', [])
.controller('AppController', ['$scope', '$document', function ($scope, $document) {
$scope.outputProductAttributeValueList = ['age', 'gender', 'all'];
// Model inputs
$scope.inputs = {};
$scope.onRankingFormSubmit = function () {
$scope.outputProductAttributeValueList.forEach(function(input) {
// Access to model inputs: $scope.inputs[input]
console.log(input + ': ' + $scope.inputs[input]);
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController" class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat="x in outputProductAttributeValueList">
{{x}} <input type="text" ng-model="inputs[x]" />
</p>
<br>
<button type="submit" ng-click="onRankingFormSubmit()">SUBMIT</button>
</div>
</div>

Angularjs - Unable to pass selected radio button value to the controller

I have a list of dynamically generated radio boxes in html:
**index.html**
<div id="choiceGraphId1" class="radio-button" ng-controller="selectGraph1">
<div ng-repeat="choice1 in choices1">
<table>
<label class="labelClass" > <td > {{choice1.graphChoice1}} </td> </label> <td>&nbsp </td> <label class="labelClass" > <td> <input type="radio" ng-model="$parent.selectedGraph1" ng-value="choice1.graphChoice1" name="graphChoice1" required /> </td> </label></table></div></div>
Angular Controller:
app.controller('selectGraph1', function ($scope,$rootScope) {
$rootScope.selectedGraph1="Choice1";
$rootScope.choices1 = [{
graphChoice1: "Choice1"
}, {
graphChoice1: "Choice2"
}
];
alert($rootScope.selectedGraph1);
});
I want to pass the value of $rootScope.selectedGraph1 to
PrintReportToPDF controller :
**index.html**
<div class="buttonsClass" ng-controller="**PrintReportToPDF**">
<button popover="Click button to open selected date range PDF Report in a new tab"
popover-trigger="mouseenter" type="button" class="btn btn-info"
ng-disabled="dataLoading"
ng-click="PrintReportToPDF()">
<i class="fa fa-file-pdf-o icon"></i>
Preview PDF Report
</button>
...
app.controller('PrintReportToPDF', function($scope, $rootScope, $window, UrlServices , StatsByDatePDF, StatsByDateExcel, Flash) {
//Preview PDF Report
alert($rootScope.selectedGraph1);
alert($rootScope.selectedGraph2);
$scope.PrintReportToPDF_1_StatisticsByDate = function() {
....
I am trying to access the $rootScope.selectedGraph1 in my controller
but its value is undefined in PrintReportToPDF controller.
What am I doing wrong here?
You can find your solution here
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
return {
name : 'anonymous'
};
});
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
}

How can I fix this Angular $scope issue?

I have a partial that uses one controller called CaseNotesCtrl. I am having problems accessing $scope variables inside of this partial. The code is this:
<div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotesCtrl">
<div class="col-sm-12 note
-field" ng-show="$parent.addingNote">
<label for="noteEntry">Enter your note</label>
<textarea class="form-control" name="noteEntry" rows="4" ng-model="newNote.note"></textarea>
<br />
</span>
<a href="" data-toggle="tooltip" data-placement="top" title="Cancel Adding Note" class="btn btn-xs btn-danger calicon-view note-cancel-button" ng-click="$parent.cancelNote();" tooltip>
<span class="glyphicon glyphicon-remove-sign"></span>
</a>
</div>
<div class="col-sm-12">
<a href="" data-toggle="tooltip" data-placement="top" title="Add a Note" class="btn btn-xs btn-danger calicon-view note-add-button" ng-click="$parent.addNote();" ng-show="!$parent.addingNote" tooltip>
<span class="glyphicon glyphicon-list-alt"></span>
</a>
</div>
<div class="col-sm-12 note-list-heading" ng-repeat-start="note in caseNotes">
<span class="note-header">Note entered by {{ note.User.DisplayName }} and was last edited on {{ note.ModifiedDate | date: "MM/dd/yyyy 'at' h:mma" }}</span></span>
</div>
<div class="col-sm-12 note-text">
{{ note.Notes }}
</div>
<div ng-repeat-end></div>
</div>
here is the controller code:
JBenchApp.controller('CaseNotesCtrl', ['$scope', '$http', '$routeParams', 'HoldState', function ($scope, $http, $routeParams, HoldState) {
// Management of case notes
$scope.NotesCaseID = $routeParams.number;
$scope.NotesUserName = localStorage.getItem('UserName');
$scope.NotesUserRole = localStorage.getItem('UserRole');
$scope.addingNote = false;
$scope.newNote = { note: 'Testing 123', CaseID: 0, NoteID: 0 };
$scope.getCaseNotes = function (CaseID, UserName, UserRole) {
$http.get('http://10.34.34.46/BenchViewServices/api/CaseNote/' + CaseID + "/" + UserRole + "/" + UserName).success(function (response) {
$scope.caseNotes = response;
})
};
$scope.saveCaseNotes = function (CaseID, UserName, NoteID) {
$scope.addingNote = false;
};
$scope.addNote = function () {
$scope.addingNote = true;
};
$scope.cancelNote = function () {
$scope.newNote.note = '';
$scope.addingNote = false;
};
$scope.editNote = function(caseID, noteID, noteText){
$scope.newNote.note = noteText;
$scope.newNote.CaseID = caseID;
$scope.newNote.NoteID = noteID;
$scope.addingNote = true;
$parent.addingNote = true;
};
$scope.getCaseNotes($scope.NotesCaseID, $scope.NotesUserName, $scope.NotesUserRole);
}]);
As you can see I am having to use $parent in places such as $parent.addingNote. If I change that to $scope.addingNote the function isn't called. The only place I am OK with $parent is $parent.isLoggedIn. How can I fix this so that it just uses $scope?
I would suggest you to use the AngularJS "Controller as" syntax when using ng-controller.
In this case it would be something like this:
app.controller('CaseNotesCtrl', function () {
this.title = 'Some title';
});
<div ng-controller="CaseNotesCtrl as caseNotes">
{{ caseNotes.title }}
</div>
So you it would be easy to you to know which scope are you working with.

angular validation not working on select

its a simple form a drop down and a save button. On page load Select should be ng-invalid because it is required and nothing is selected but form and select both are ng-valid and save function is called.
and once i select any thing and un select it. then it behaves properly.
<form role="form" name="frmVariableConfig" id="frmVariableConfig" novalidate ng-submit="frmVariableConfig.$valid && saveChanges()">
<div>
<div class="form-group">
<div class="form-group control-group">
<span>Logic</span>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="CurrCustomer.Logic"
ng-options="service.ServiceID as service.ServiceName for service in services"
required="">
<option value="">Select Service</option>
</select>
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-sm text-right">Save</button>
</div>
</form>
where the controller code looks like this.
(function () {
'use strict';
var controllerId = 'dashboard';
angular.module('app').controller(controllerId, ['$scope', dashboard]);
function dashboard($scope) {
$scope.CurrCustomer = {};
$scope.CurrCustomer.Logic = false;
$scope.saveChanges = function () {
alert('function called');
};
$scope.services = [
{ ServiceID: 1, ServiceName: 'Service1' },
{ ServiceID: 2, ServiceName: 'Service2' },
{ ServiceID: 3, ServiceName: 'Service3' }
];
}})();
You need to remove the setter $scope.CurrCustomer.Logic = false; from your controller that is filling that ng-model and making it valid on controller load. After filling that CurrCustomer.Logic value it become valid input as it is required.

Categories