Adding a variable to a group of array - html

I'm using angular js to produce to add an array and display it as we go along. So far the given code adds an array to the list but it doesn't keep adding the array with the press of the function.
I'm quite new to angular and i think there's something I'm missing but right now I'm stuck.
The html code has a button linked which is supposed to carry out the function.
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = ["Testing Task 5.1", "Downloaded Task 5.1"];
$scope.addArray = function() {
$scope.records.unshift("saddfadffas")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="myCtrl" class="container">
<p>
<h3>Status: </h3>
<input type="text" ng-model="additem">
<button ng-click="addArray()">function</button>
</p>
<ul ng-repeat="x in records">
<li>{{x}}</li>
</ul>
</div>

You can resolve this issue by having the items in your array be keyed by their position rather than their value. To do this, you can use track by $index. Hope this helps!
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = ["Testing Task 5.1", "Downloaded Task 5.1"];
$scope.addArray = function() {
$scope.records.unshift("saddfadffas")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl" class="container">
<p>
<h3>Status: </h3>
<input type="text" ng-model="additem">
<button ng-click="addArray()">function</button>
</p>
<ul ng-repeat="x in records track by $index">
<li>{{x}}</li>
</ul>
</div>

Try push rather thanunshift? Sorry I am not at my computer right now so can't verify this, but I'm pretty sure this will solve the problem

EDIT: Perhaps your intention is
$scope.records.unshift($scope.additem)
rather than
$scope.records.unshift("saddfadffas")
but I am assuming you are perhaps running into an error we can't see from the excerpt you posted.

Related

how to add the value written inside checkbox by user?

I wrote this code for add and remove Textboxes using AngularJS, but I want to add the value of checkbox which will written by user and display it on same page so what can I do it?
The code below will display 1 textbox and 3 buttons, if I click on append then it will add one more text box on page and when I click on remove then it will remove last checkbox.
And I want to add functionality for example if I append 4 checkboxes, and every checkbox I insert some values as number, then I click on add button then it will return the addition of values which I inserted before and return it on same page. so what should i write in code
var app = angular.module('abc', []);
app.controller('myCtrl', function($scope) {
$scope.array=[1];
});
<html ng-app="abc" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-repeat="a in array">
Textbox {{a}} <input type="text" id="{{a}}">
</div>
<button ng-click="array.push(array.length+1)">Append</button>
<button ng-click="array.pop(array.length-1)">Remove</button>
<button>Add</button>
</body>
</html>
You can create a calcSum function in the scope, which calculates the sum of the entered values and stores the sum in the scope. Then you can call that function with ng-click.
Note that I changed your array to directly contain the values entered in the textbox. This way you can directly calculate the sum of the array without having to loop through the inputs manually.
var app = angular.module('abc', []);
app.controller('myCtrl', function($scope) {
$scope.array=[0];
$scope.calcSum = function() {
$scope.sum = $scope.array.reduce(function(total, num) {
return total + num;
})
}
});
<html ng-app="abc" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-repeat="a in array track by $index">
Textbox {{$index}} <input type="number" ng-model="array[$index]">
</div>
<button ng-click="array.push(0)">Append</button>
<button ng-click="array.pop(array.length-1)">Remove</button>
<button ng-click="calcSum()">Add</button>
<div>{{sum}}</div>
</body>
</html>

How can I use ng-bind-html inside my directive?

I'm using templates based on my JSON. So, I can't really use my ng-bind-html like I would normally do.
Seems like the only option I have is to use my sanitized html inside an directive.
Looking for similar questions, I couldn't figure it out how to apply in my case.
Yes, I am pretty newbie into angular.
I'm currently receiving this data from my controller:
$scope.safecontainers = $sanitize($scope.containersmsg);
In my html would normally be like this:
<p ng-bind-html="containersmsg"></p>
But I don't want this, I need to use this ng-bind-html inside a directive!
Some people have talked about $compile, but I couldn't really figure it out how to apply in my case.
EDIT:
Based on comments, i'll add more code to help you guys further understand my goal.
Inside my index.html I'm declaring the controllers needed and calling my
<ng-view></ng-view>
Then, based on what I receive, i'll load one view or another:
<div ng-if='setores[0].SetorTema == "1"'>
<theme-one titulo="{{setores[0].SetorNome}}" logo="
{{setores[0].SetorLogo}}" evento="{{evento[0].EventoNome}}">
</theme-one>
// I omitted some of the parameters because they ain't relevant
</div>
My template is like this: (Just a little part of it to avoid much useless code)
<section class="target">
<div class="col-md-6 col-xs-12">
<div class="" ng-repeat="banner in title">
<div class="target-title">{{ banner.BannerLevelTitulo }}
</div>
<div class="target-desc">{{banner.BannerLevelDescricao}}</div>
</div>
</div>
<div class="col-md-6 col-xs-hidden">
<div class="target-image"><img ng-src="{{targetimage}}" alt="">
</div>
</div>
</section>
This is the controller I want my sanitized code.
hotsite.controller('containerController', function($scope, $http, $sanitize)
{
$scope.containers = [];
$scope.containersmsg = '';
$scope.safecontainers = $sanitize($scope.containersmsg);
$http.get('/Admin/rest/getContainer')
.then(function onSuccess(response) {
var data = response.data;
$scope.containers = data;
$scope.containers = response.data.filter(containers =>
containers.ContainerAtivo);
$scope.containersmsg = $scope.containers[0].ContainerDesc;
})
.catch(function onError(response) {
var data = response.data;
console.log(data);
});
});
This is a piece of my directive:
angular.module('hotsiteDirectives', [])
.directive('themeOne', function($compile) {
var ddo = {};
ddo.restrict = "AE";
ddo.transclude = true;
ddo.scope = {
titulo: '#',
...
(a lot of other scope's)
contimg: '#'
};
ddo.templateUrl = 'app/directives/theme-one.html';
return ddo;
})
And yes, I am calling the ngSanitize
var hotsite = angular.module('hotsite',['ngRoute', 'hotsiteDirectives',
'ngSanitize']);
TL;DR
This is how my code looks like inside a directive, with raw html and not rendered:
This is how it works with ng-bind-html, formatted html
If I do put this inside my view
<p ng-bind-html="containersmsg"></p>
It will be alright, all of it working like it should.
BUT, I need to call this only inside my directive, and I don't know how to do it.
So, with this context:
How can I put my sanitized html inside my directive and template?
You don't even have to trust the html to render it using ngBindHtml because the directive already does it for you. You basically need to create a parameter attribute for your directive to hold the html string, so, inside the directive's template, you use ng-bind-html="myParam".
The following snippet implements a simple demonstration of creating a directive that receives and renders an html input parameter that comes from a controller.
angular.module('app', ['ngSanitize'])
.controller('AppCtrl', function($scope) {
$scope.myHtml = '<div><b>Hello!</b> I\'m an <i>html string</i> being rendered dynamicalli by <code>ngBindHtml</code></div>';
})
.directive('myDirective', function() {
return {
template: '<hr><div ng-bind-html="html"></div><hr>',
scope: {
html: '='
}
};
});
<div ng-app="app" ng-controller="AppCtrl">
<my-directive html="myHtml"></my-directive>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-sanitize.js"></script>

angularjs post web service dropdown

I have created a web application with Eclipse where I use AngularJS and REST GET web services. Through the web services I query my MySQL database for data and send the values to my html page through controlles http GET controllers.
I successfully show dropdown lists with the database values in my HTML page. Now I want to send the selected items for each dropdown list back to a java page so that I can create a new query that will produce some new data. But I don't know how I can do this second part, can someone help me with it?
Thanks in advance!
this is part of my html page
<div id="three" ng-controller="mycontroller">
<table class="table table-hover">
<tbody>
<select ng-model="selecteditem">
<option ng-repeat="item in items">
{{item.itemname}}
</option>
</select>
</tbody>
</table>
<b>You selected: {{selecteditem}}</b>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('showitems', function($scope, $http) {
$http.get('http://localhost:8080/myproject/REST/WebService_items/GetItems').
success(function(data) {
$scope.items = data;
})
.error(function() {
$scope.items = "error in fetching data";
});
});
</script>
Thanks for both answers! My main issue is not how to show the items in the drop down lists, I have done that. I want to send the selected items to a Java page of my project through a REST web service function, so I don't know how to write the angularjs code in my HTML page that will send push/post the items in the web service's URL.
<label>example</label>
<md-select id="example" ng-model="vm.list.example" required>
<md-option ng-repeat="unit in vm.list" value="{{example.id}}">{{example.name}}</md-option>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="three" ng-controller="mycontroller">
<table class="table table-hover">
<tbody>
<select ng-model="selecteditem">
<option ng-repeat="item in items">
{{item.itemname}}
</option ng-click="callTheFunction(item.itemname})">
</select>
</tbody>
</table>
<b>You selected: {{selecteditem}}</b>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('mycontroller', function($scope, customService) {
$scope.items = [{itemname:'apple'},{itemname:'mango'}]
$scope.callTheFunction=function(itemSelected){
customService.restCallToJava(itemSelected)
}
app.service('customService',['$http', function($http) {
var restCallToJava= function(sensorObj){
return $http.post('/api',sensorObj);
}
}])
</script>

How to Resolve Angular Scope Variable Inside Div Class

<div class="progressMain">
<div class="stocking progressWrap progress" data-progress-percent="33">
<div class="progressBar progress stocking"></div>
<div class="progressText">In Progress 3 of 7 steps</div>
</div>
</div>
I have data-progress-percent value in my directive scope but I am not sure how I can resolve scope value inside data-progress-percent.
I tried data-progress-percent={{value}} but it didn't work.
Any idea how I can resolve scope variable inside div class ?
Have a scope variable in your controller to be passed to your directive. Then use directive template to display the percent value(may be after some calculation in your directive link's function).
DEMO - http://plnkr.co/edit/8DZzSjcpDqRworpxQrAs
HTML:
<body ng-app="myApp" ng-controller="myController">
<div class="progressMain">
<div class="stocking progressWrap progress" progress-percent="percentValue">
</div>
</div>
<br/><br/>
<div>Enter percentage value to be passed to directive and used as in directive template:</div>
<br/>
<input type="text" ng-model="percentValue" />
</body>
JS:
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.percentValue = 33;
});
app.$inject = ['$scope'];
app.directive('progressPercent', function () {
return {
restrict: 'A',
template: '<div class="progressBar progress stocking"></div><div class="progressText">In Progress {{percentValue}} steps</div>'
};
});
Hope it helps.
Use $timeout(). It will solve your problem.
$timeout() will run in the next $digest cycle.

AngularJS - How to bind multiple dynamically added elements to other elements in different sections of HTML?

I apologize if I worded the question incorrectly, I am attempting to build a survey builder and I am running into a problem. Here is the link to an example plunker:
Updated:
plunker
JS:
(function() {
var app = angular.module('FormBuilder');
var stageController = function($scope, componentBuilder) {
//var test = "<div>test<button>Im a Button</button></div>";
$scope.components = [];
$scope.components2 = [];
$scope.selectedComponentIndex = -1;
//$scope.list = [{html:test}];
//$scope.componentSettings = "";
$scope.showComponentSettings = function(componentName, index) {
$scope.componentSettings = componentName;
$('#navTab a[href="#componentSettingsPage"]').tab('show');
};
$scope.addMultipleChoice = function() {
var component = componentBuilder.createMultipleChoice();
$scope.components2.push(component);
$scope.components.push(component.name);
};
$scope.addTextEntry = function() {
var component = componentBuilder.createTextEntry();
$scope.components.push(component);
};
$scope.addReadOnlyTextEntry = function() {
var component = componentBuilder.createReadOnlyTextEntry();
$scope.components.push(component);
};
$scope.delete = function(index) {
$scope.components.splice(index, 1);
};
};
app.controller("stageController", stageController);
}());
HTML:
<body>
<div ng-controller="stageController">
<!-- div>
<div ui-sortable="" ng-model="list">
<div ng:repeat="item in list" class="item">
{{item}}
</div>
</div>
</div-->
<div>
Value of scope.inner = {{components}}
</div>
<div style="display: table-row">
<div ng-include="" src="'nav.html'" style="width: 300px; display: table-cell;"></div>
<div ng-include="" src="'stage.html'" style="display: table-cell;"></div>
</div>
</div>
<script type="text/ng-template" id="multipleChoice">
<div class="multipleChoice"></div>
</script>
<script type="text/ng-template" id="textEntry">
<div class="textEntry"></div>
</script>
<script type="text/ng-template" id="readOnlyTextEntry">
<div class="readOnlyTextEntry"></div>
</script>
UPDATED question and example:
Please see my current plunker for the problem I am having. The plunker shows an example form builder that allows a user to added various components to build a form, this example allows multiple choice, text entry, and read only text entry components.
The left nav contains two tabs, one for the components and another for custom settings such as changing the question label or adding more choices to a component. My current problem is that I don't know the best method/practice to bind elements on the item settings to a specific form component in the collection.
So if a user adds a multiple choice component, clicks on it, it will show the item settings, and then be able to modifying the component settings for that specific component.
I hope this is more clear, any help is appreciated, thank you in advance.