Angular: Push item to list doesn't update the view - javascript

When I push an item to an array, the view won't refresh the list.
table:
<tbody id="productRows">
<tr data-ng-repeat="product in products | filter: search">
<td>{{ product.Code}}</td>
<td colspan="8">{{ product.Name}}</td>
</tr>
</tbody>
form:
<form data-ng-submit="submitProduct()">
Code:
<br />
<input type="text" required data-ng-model="product.Code"/>
<br />
<br />
Naam:
<br />
<input type="text" required data-ng-model="product.Name"/>
<br />
<input type="submit" value="Opslaan" />
</form>
submitProduct in controller:
$scope.submitProduct = function () {
console.log('before: ' + $scope.products.length);
$scope.products.push({Code: $scope.product.Code, Name: $scope.product.Name});
console.log('after:' + $scope.products.length);
console.log($scope.products);
$scope.showOverlay = false;
};
As you can see, I log the total items in the array and it behaves like I would expect. The only thing that doesn't do what I expect is the content of my table, that doesn't show the new value.
What do I have to do, so the new row is displayed in the table?

I can't see the rest of your code, but make sure $scope.products is defined in your controller.
See this example.
The only addition I made to the code you provided was:
$scope.products = [];
If this doesn't help then please provide more information.

Thanks for the answer and the comments. The problem was at another place. In my routeProvider I had declared a controller. I also had a ng-controller directive in my div. So my controller gets executed twice. When I removed the ng-controller directive, everything was just working as it should be :)

Related

How to share information from one controller to another using a service?

I have doubts about how to share my data between two controllers.
I currently have two "div" with two controllers.
The PriceController driver calls a REST service. The service returns a price matrix that exists in a database and loads the data (objects) in a table.
In the FormController, the form information is obtained and updated in the database.
Desired functionality:
When you click on the "Edit" button, the information is loaded in the form.
The form allows you to edit the "Price" field.
By pressing the "Save" button of the form, it is updated in the database.
I made an example of what I want. The service to save the data in the database is done, so I did not put it in the example..
Questions:
Is it convenient to implement the use of ng-model? How?
Is it necessary to use ngModelOptions?
How can I send the data of my form to the database?
The connection between controllers is correct?
Can you give me an idea?
Example application
Example in JsFiddle
app.js
angular.module("app", [])
.factory("Service", function(){
var data={}
return data;
})
.controller("FormController", function($scope, Service){
$scope.service = Service;
$scope.updateData = function(data){
//TODO: Implement logic to update database
}
})
.controller("DataController", function($scope, Service){
$scope.service = Service;
// Fake database
$scope.dataPrices = [
{
code: 'AA',
price: 111
},
{
code: 'BB',
price: 222
},
{
code: 'CC',
price: 333
}
];
$scope.editData = function(index){
$scope.service.data = $scope.dataPrices[index];
}
});
index.html
<div ng-app="app">
<div ng-controller="FormController" >
<form name="mainForm" novalidate>
<div>
<label>Code</label>
<div>
<input
type="text"
name="code"
ng-required="true"
ng-disabled="true"
value="{{service.data.code}}"
/>
</div>
</div>
<div>
<label>Price</label>
<div>
<input
type="number"
name="price"
ng-required="true"
value="{{service.data.price}}"
/>
</div>
</div>
<div>
<button
type="submit"
ng-click="updateData(data)">
Save
</button>
</div>
</form>
</div>
<div ng-controller="DataController">
<table>
<tr>
<th>Code</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr ng-repeat="dat in dataPrices">
<td>{{dat.code}}</td>
<td>{{dat.price}}</td>
<td>
<button ng-click="editData($index)">
Edit
</button>
</td>
</tr>
</table>
</div>
</div>
Excuse me for my English.
Thank you.
A response to your questions:
Is it convenient to implement the use of ng-model? How?
You can use ng-model like this:
<input ... ng-model="service.data.code" />
Is it necessary to use ngModelOptions?
No its not necessary but it may be useful in some circumstances - https://docs.angularjs.org/api/ng/directive/ngModel
How can I send the data of my form
to the database?
You can post it off to the backend using fetch:
fetch(endpoint, Service.data).then(response => console.log(response))
The connection between controllers is correct?
Yes, using a service is the best approach to sharing data between controllers.

Why is my AngularJs 'add' button only working once?

I'm just starting out with Angular.
I've written some code that downloads a JSON array configuredAPIs and displays each object within it, <div ng-repeat="capi in configuredAPIs">. For each of these, there's another directive to list the items from an array of strings, <tr ng-repeat="eurl in capi.externalURLs">
Underneath there's a text box to add a new string to this array, which I've bound to a $scope variable called url.
When I click the 'add' button, everything works - the new string is added to the array, a new row appears in the table.. ..but it only works once. Subsequent clicks on the 'add' button add empty strings to the array (and thus empty text boxes).
What have I done wrong?
index.html
<div ng-app="testApp" ng-controller="testCtrl">
<div ng-repeat="capi in configuredAPIs">
<h1>Configured API</h1>
<p>
Name:
{{ capi.name }}
</p>
<h2>External URLs</h2>
<form ng-submit="addExternalURL(capi)">
<table>
<!-- A row in the table for each string in the array -->
<tr ng-repeat="eurl in capi.externalURLs">
<td>
<input type="text" ng-model="eurl" />
</td>
</tr>
<!-- Final table row to add a new string to the array -->
<tr>
<td>
<input type="text" ng-model="url" placeholder="Enter a new external URL">
<input class="btn-primary" type="submit" value="add">
</td>
</tr>
</table>
</form>
</div>
</div>
controller.js
var app = angular.module('testApp', []);
app.controller('testCtrl', function ($scope, $http) {
$scope.url = 'new url';
$http.get("/api/configuredapis?orgid=2")
.success(function (response) { $scope.configuredAPIs = response; });
$scope.addExternalURL = function ($capi) {
$capi.externalURLs.push($scope.url);
$scope.url = '';
};
});
It is because AngularJS does not watch and update primitives (e.g. strings, numbers, booleans) the way one obviously thinks it does.
So instead you bind objects with values to the scope or use a function which returns the primitive value.
See:
https://github.com/angular/angular.js/wiki/Understanding-Scopes
http://www.codelord.net/2014/05/10/understanding-angulars-magic-dont-bind-to-primitives/
Example for using an object (at controller):
$scope.primitives = {
url : 'foo://'
}
And within the template:
<input type="text" ng-model="primitives.url">
So what happens in your example is that once you set it to '' the changes to the model within the template are not recognized anymore.

how to get ng-repeat checkbox values on submit function in angularjs

I have a form which has 10 checkboxes. By default angular js triggers on individual checkbox. I want to grab all selected check box values on submit action only. Here is my code...
<form name="thisform" novalidate data-ng-submit="booking()">
<div ng-repeat="item in items" class="standard" flex="50">
<label>
<input type="checkbox" ng-model="typeValues[item._id]" value="{{item._id}}"/>
{{ item.Service_Categories}}
</label>
</div>
<input type="submit" name="submit" value="submit"/>
</form>
$scope.check= function() {
//console.log("a");
$http.get('XYZ.com').success(function(data, status,response) {
$scope.items=data;
});
$scope.booking=function(){
$scope.typeValues = [];
console.log($scope.typeValues);
}
I am getting empty array.
Can somebody tell how to grab all selected checkbox values only on submit event.
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.SELECTED" ng-true-value="Y" ng-false-value="N"/>
</div>
<input type="submit" name="submit" value="submit" ng-click="check(items)"/>
$scope.check= function(data) {
var arr = [];
for(var i in data){
if(data[i].SELECTED=='Y'){
arr.push(data[i].id);
}
}
console.log(arr);
// Do more stuffs here
}
Can I suggest reading the answer I posted yesterday to a similar StackOverflow question..
AngularJS with checkboxes
This displayed a few checkboxes, then bound them to an array, so we would always know which of the boxes were currently checked.
And yes, you could ignore the contents of this bound variable until the submit button was pressed, if you wanted to.
As per your code all the checkboxes values will be available in the typeValues array. You can use something like this in your submit function:
$scope.typeValues
If you want to access the value of 3rd checkbox then you need to do this:
var third = $scope.typeValues[2];
Declare your ng-model as array in controller, like
$scope.typeValues = [];
And in your template, please use
ng-model="typeValues[item._id]"
And in your controller, you will get this model array values in terms of 0 and 1. You can iterate over there.

How to check all checkboxs with angular

I have a checkbox that should check all checkboxes. The checkbox works as it should by checking all the checkbox's, however angular doesnt think they have been checked? The only way angular knows if they are checked is if i manually check each one. (The brackets and for loop are blade php from laravel)
<label class="checkbox-inline">
<input type="checkbox" ng-model="everyoneCheck"/> Everyone
</label>
#foreach($company->users as $tagIndex => $user)
<label class="checkbox-inline">
<input type="checkbox" ng-checked="everyoneCheck" ng-model="newDiscussion.notify_partners[{{$tagIndex}}]" ng-true-value="{{$user->id}}" /> {{ $user->first_name }} {{ $user->last_name }}
</label>
#endforeach
upon click of the submit button i proceed to $http.post to my server, i just pass in an object to the post function, this is the object.
var discussionData = {
'title': $scope.newDiscussion.title,
'discussion': $scope.newDiscussion.summary,
'company_id': company_id,
'notify_partners': $scope.newDiscussion.notify_partners
};
for some reason when i use the check all approach, nothing gets put into notify_partners, however when i manually click each checkbox, they will get entered and submitted properly.
Any help? I feel like its some sort of binding issue, where i just need to tell angular, hey its updated!
Here's a way to do it:
<p><input type="checkbox" ng-model="globalCheck" ng-click="toggleCheckAll()" /> Check All</p>
<ul>
<li ng-repeat="i in init">
<input type="checkbox" ng-model="checkbox[$index]" /> Checkbox {{ $index + 1 }} {{ checkbox[$index] }}
</li>
</ul>
Then in your controller:
function myControl($scope) {
$scope.globalCheck = false;
$scope.checkbox = {};
$scope.init = [0,1,2,3,4,5,6,7,8,9];
$scope.toggleCheckAll = function() {
var k, val = !$scope.globalCheck;
console.log(val);
for(k in $scope.init) {
$scope.checkbox[k] = val;
}
}
}
See JSfiddle for working example
ng-checked does not update the value bound in ng-model. It only affects the presence of the checked attribute on the element itself.
Your best bet is to use ng-change to execute some function and update all your models accordingly.
<input type="checkbox"
ng-model="everyoneCheck"
ng-change="toggleCheckAll()"/>
And in your controller, you can have toggleCheckAll() loop over your models and set them based on the value of everyoneCheck

Make AngularJS page double as search results page

I have a basic table in which I'm displaying data, as pulled from a database, through AngularJS. I also have a search field that uses AngularJS to filter the data:
<input ng-model="search" id="search" type="text" placeholder="Search" value="">
<div ng-controller="eventsController")>
<table>
<tr ng-repeat="event in events | filter:search">
<td><span ng-bind="event.title"></span></td>
<td><span ng-bind="event.date_start"></span></td>
</tr>
</table>
</div>
<script>
function EventsController($scope, $http) {
$http.get('/api/all-events').success(function(events) {
$scope.events = events;
});
}
</script>
This is great for user-defined searches, but what if I want to run a particular filter upon page load while maintaining the search functionality? Is there a way that I can use AngularJS to automatically filter the results based on a URL parameter (i.e. example.com?search=foo)? Ideally, the value of the the input field would also be set to the URL parameter.
Like the comments said, this has nothing to do with filter. It's more about how you organize your code to customize URL path you send to the server. You can try to do it this way:
function EventsController($scope, $http) {
// this field is bound to ng-model="search" in your HTML
$scope.search = 'ALL';
$scope.fetchResults = function() {
var path;
if ($scope.search === 'ALL') {
path = '/api/all-events';
} else {
path = '/search?input=' + $scope.search;
}
// here we send different URL path
// depending on the condition of $scope.search
$http.get(path).success(function(events) {
$scope.events = events;
});
};
// this line will be called once when controller is initialized
$scope.fetchResults();
}
And your HTML code, make sure your controller is on the parent div of the input field and search button. And for the search button, you invoke fetchResults() when it's clicked:
<div ng-controller="eventsController")>
<input ng-model="search" id="search" type="text" placeholder="Search" value="">
<button ng-click="fetchResults()">Search</button>
<div>
<table>
<tr ng-repeat="event in events | filter:search">
<td><span ng-bind="event.title"></span></td>
<td><span ng-bind="event.date_start"></span></td>
</tr>
</table>
</div>
</div>

Categories

Resources