Showing products with angular in the html - javascript

I'm trying to make a table that shows products with angular, but the items are not showing up in HTML. If anyone notice anything wrong with the code, please help me.
This is my app.js:
(function (){
var app = angular.module('confirmados', []);
app.controler('ListaController', function (){
this.product = gem;
});
var gem = {
id: 1,
name: 'cool',
email: 'cool#'
};
And this is my HTML:
<tr ng-controller="ListaController as lista" class="reservas">
<td> {{lista.product.id}} </td>
<td> {{lista.product.name}} </td>
<td> {{lista.product.email}} </td>
</tr>

You spelled controller wrong:
app.controler
Should be
app.controller

Related

KnockoutJs: dataObject is not defined

I have a simple WebApi project to manipulate returned data in various format. I am trying to use KnockoutJs to consume the data at the front end but I am having a variable not defined error that I can't seem to understand why. Below is the simple code I am working on. Please feel free to point out the errors. Thanks
Controller formats
[httpGet]
public Object Data
{
return new {
Time: DateTime.now,
Text: "<b>Salut</b>",
Count: 1
};
}
JS front end
<script>
$(document).ready(function(){
$.ajax("/api/formats", {
success: function(data){
dataObject = ko.observable(data);
ko.applyBindings();
}
};
});
HTML
<tbody>
<tr>
<td>Time</td>
<td data-bind="text: dataObject().Time">
<td>Text</td>
<td data-bind="text: dataObject().Text">
</tr>
</tbody>
At first,your variable dataObject does not have Time and Text properties, so you should check it in your code as following:
var dataObject = ko.observable();
ko.applyBindings();
function doBinding() {
var data = {
Time: "XYZ",
Text: "<b>Salut</b>",
Count: 1
};
dataObject(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div>
<div data-bind="text: dataObject() ? dataObject().Time : 'No Data'"></div>
<div data-bind="text: dataObject() ? dataObject().Text : 'No Data'"></div>
<div>
<button onclick="doBinding()">binding</button>

Angularjs ng-model not working input[text])

I have a data from the database in a loop and this works great, and the value is in input field, but when i want read this value after click angular return me:
Object {newName: undefined, newEmail: undefined}
and i don't know why. Please for help.
HTML CODE:
<tr ng-repeat="user in users">
<td><input type="text" ng-model="user.name" name="user.name" ></td>
<td><input type="text" ng-model="user.email" name="user.email" ></td>
<td><button ng-click="checkData()">Click</button></td>
</tr>
CONTROLLER CODE:
$scope.user = {};
$scope.checkData = function () {
var data = {
newName: $scope.user.name,
newEmail: $scope.user.email
};
console.log(data);
Inside your ng-repeat code you have displayed each element of users & you are showing the one below another inside tr of table. While you wanted to access the element which you are editing, You need to pass that user object to the checkData method so that you can have access to that specific specific user.
Markup
<tr ng-repeat="user in users">
<td><input type="text" ng-model="user.name" name="user.name" ></td>
<td><input type="text" ng-model="user.email" name="user.email" ></td>
<td><button ng-click="checkData(user)">Click</button></td>
</tr>
Code
$scope.checkData = function (user) {
var data = {
newName: user.name,
newEmail: user.email
}
console.log(data);
};
In your ng-click pass the user model such that it becomes ng-click="checkData(user)"
Then, rewrite your controller code as:
$scope.user = {};
$scope.checkData = function (user) {
console.log(user);
};
You need to give the function the data from the DOM you want to evaluate, which is the current user:
You can use
<tr ng-repeat="user in users">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td><button ng-click="check(user)"></button></td>
</tr>
$scope.check = function (thing) {
var currentUser = {
name: thing.name,
email: thing.email
}
}

Get filtered data only on model object as result, angularjs

My code is like this
<body ng-app="myApp" ng-controller="MainCtrl">
<div>Name only
<input ng-model="search.name" />
<br />
<table id="searchObjResults">
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
<tr ng-repeat="friendObj in friends | filter:search:strict | limitTo:1">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</div>
<div>
<button type="button" id="btn_submit" ng-click="submitForm()">Get rates</button>
</div>
angular.module('myApp', []).controller('MainCtrl', ['$http', '$scope', function ($http, $scope) {
$scope.friends = [{
name: 'John',
phone: '555-1276'
}, {
name: 'Mary',
phone: '800-BIG-MARY'
}, {
name: 'Mike',
phone: '555-4321'
}, {
name: 'Adam',
phone: '555-5678'
}, {
name: 'Julie',
phone: '555-8765'
}, {
name: 'Juliette',
phone: '555-5678'
}];
$scope.submitForm = function () {
// i want to get the data here
};
}]);
As you can see at a time only one friend will be active on my screen. when I press my submit button, I want that data (filtered single row) to be the only value on my current $scope.friends so that I can send it to an external service as the selected data. Can any one point out what i need to do here
Fiddle
Note: I can't change the position of this button.
Why not make your button part of the table row, since there will only ever be one? Here is a JSFiddle showing it working in that fashion.
The ng-click function handler for the button can then simply take a parameter that is the actual friendObj you are interested in:
<button type="button" ng-click="submitForm( friendObj )">Get rates</button>
EDIT: There is actually a way to do this if you can't move the button; make the ng-repeat operate over a NEW array, which will be accessible outside of the ng-repeat. So your ng-repeat statement becomes:
<tr ng-repeat="friendObj in newArray = (friends | filter:search:strict | limitTo:1)">
And then your button can simply reference the one-element array:
<button type="button" ng-click="submitForm( newArray )">Get rates</button>
Updated Fiddle here :-)
Try this:
$scope.submitForm = function () {
var data = $filter('filter')($scope.friends, $scope.search.name);
};
Fiddle here.
If you put the filter in the controller instead of the view, you could set a variable like $scope.result that the submitForm function could use. For example, in your HTML, you could add an ng-change directive to your search field like so:
<input ng-model="search.name" ng-change="updateResult()" />
Then, instead of using ng-repeat, you'd use ng-show to show the one result, or hide the row if there is no result:
<tr ng-show="result">
<td>{{result.name}}</td>
<td>{{result.phone}}</td>
</tr>
Then in your controller:
$scope.search = {name: ''};
$scope.updateResult = function() {
$scope.result = $filter('filter')($scope.friends, $scope.search.name)[0];
}
$scope.updateResult();
// ...
$scope.submitForm = function() {
// $scope.result can be used here
}
EDIT: The advantage of this approach is it's a bit DRYer because you don't re-filter inside submitForm. MarcoS's approach has the advantage of being a lot shorter!

Manipulating array data to actually save, write, and change the data content

I am new to AngularJS and so far I'm loving it but I am having a hard time manipulating my data with it. I have an array of data with the attributes name:'', description:'', type:'', ... etc ... and I have enough data but not enough yet for me to upload it onto a server. My problem is that I want to be able to change and update my data using a form or input.
Here is my scripts/admin.js where I implement function submitTheForm() that I call with the submit button.
angular.module('myApp')
//filter to get a specific $scope.campaigns using its id
.filter('getById', function() {
return function(input, id) {
var i=0, len=input.length;
// alert(input.length);
for (; i<len; i++) {
if (+input[i].id === +id) {
return input[i];
}
}
return input[0];
};
})
.controller('AdminCtrl', ['$scope', '$filter', function($scope, $filter) {
//<--ARRAY OF DATA with multiple attributes<--
$scope.campaigns = [
{ name:'', description'', etc... etc...},
{...Lots of Data...},
{...Lots of Data...},
{...Lots of Data...},
{...Lots of Data...},
];
$scope.selectCampaign = function(object) {
$scope.selectedCampaign = object;
};
$scope.submitTheForm = function(item, event) {
if (confirm("Are you sure you want to edit?") == true) {
alert("--> Submitting form");
var dataObject = {
name : $scope.selectedCampaign.name, description: $scope.selectedCampaign.description, type: $scope.selectedCampaign.type, imgSrc: $scope.selectedCampaign.imgSrc, brand: $scope.selectedCampaign.brand, region: $scope.selectedCampaign.region, location: $scope.selectedCampaign.location, contact: $scope.selectedCampaign.contact, url: $scope.selectedCampaign.url, id: $scope.selectedCampaign.id
};
console.log(dataObject);
var campaign = $scope.selectedCampaign;
var id = campaign.id;
var found = $filter('getById')($scope.campaigns, id);
// setTimeout(function(){ $scope.$apply($scope.selectedCampaign = dataObject); });
}
};
}]);
Here is my main.html where I have my input and submit button
<div class="row modalDetail">
<div class="col-xs-12 col-sm-6 col-md-6 detailLeft text-left">
<div class="middle-allign">
<h1 class="detailName">
<input type="text" ng-model="selectedCampaign.name" name="name">
</h1>
<div class="detailDescription">
<textarea rows="5" cols="71" name="description" ng-model="selectedCampaign.description"></textarea>
</div>
<table class="detailTable table">
<tbody>
<tr>
<td class="bolder">Brand</td>
<td>
<input type="text" ng-model="selectedCampaign.brand" name="brand" >
</td>
</tr>
<tr>
<td class="bolder">Campaign Type</td>
<td>
<input type="text" ng-model="selectedCampaign.type" name="type">
</td>
</tr><tr>
<td class="bolder">Region</td>
<td>
<input type="text" ng-model="selectedCampaign.region" name="region">
</td>
</tr>
<tr>
<td class="bolder">Contact</td>
<td>
<input type="text" ng-model="selectedCampaign.contact" name="contact">
</td>
</tr>
<tr>
<td class="bolder">Location</td>
<td>
<input type="text" ng-model="selectedCampaign.location" name="location">
</td>
</tr>
<tr>
<td class="bolder">URL</td>
<td>
<input type="text" ng-model="selectedCampaign.url" name="url">
</td>
</tr>
</tbody>
</table>
<div class="detailCta">
<button class="btn detailButton" ng-click="submitTheForm()">Submit Campaign</button>
</div>
</div>
</div>
I am trying to utilize 'ng-model' to bind the data and it all works fine but it does not actually change the array content within my main.html. When I refresh it all just goes back to how my array content is. This is because I haven't actually over-written my array content. How can I go about making a absolute change/over-write to the actual object within the array content?
I feel as though it is as simple as $scope.campaigns.push(campaign); except instead of 'push' it would be 'update' or 'over-write'
If you want to store the values in the server, you should see ngResource to create entry points to get and save (and delete) data. Alternatively, you can use the lower level service $http.
If you want to store the data in your current script (it will last until the page is refreshed in the browser - F5), you should do some changes:
.controller('AdminCtrl', ['$scope', '$filter', '$rootScope', function($scope, $filter, $rootScope) {
//<--ARRAY OF DATA with multiple attributes<--
if ($rootScope.campaigns === undefined) {
$rootScope.campaigns = [
{ name:'', description'', etc... etc...},
{...Lots of Data...},
{...Lots of Data...},
{...Lots of Data...},
{...Lots of Data...},
];
}
$scope.campaigns = $rootScope.campaigns;
//don't even think this above line is needed, since $scope inherits from $rootScope, but I've put it for clarity.
$scope.selectCampaign = function(object) {
$scope.selectedCampaign = object;
};
$scope.submitTheForm = function(item, event) {
if (confirm("Are you sure you want to edit?") == true) {
alert("--> Submitting form");
var dataObject = {
name : $scope.selectedCampaign.name, description: $scope.selectedCampaign.description, type: $scope.selectedCampaign.type, imgSrc: $scope.selectedCampaign.imgSrc, brand: $scope.selectedCampaign.brand, region: $scope.selectedCampaign.region, location: $scope.selectedCampaign.location, contact: $scope.selectedCampaign.contact, url: $scope.selectedCampaign.url, id: $scope.selectedCampaign.id
};
console.log(dataObject);
var campaign = $scope.selectedCampaign;
var id = campaign.id;
var found = $filter('getById')($scope.campaigns, id);
}
};
}]);
Notice how I bind it to $rootScope.campaigns - so if you navigate to another ng-view and then come back, the data is still here.
However, if you want your data survive the F5, you must either use the server side options I gave you. or use Local Storage.

Programmatically inserting array values in Angular JS

Update: I was able to solve it by changing how I was calling the push method. Refer to the inline comments in the snippet. Thanks SO for the help. Any comments / thoughts on why this is not a good idea would be highly appreciated.
I have an Angular JS array that is bound to my UI. When I add an item to it via the UI, it works fine and my UI is updated with the newly added item. So, this code works...
//The HTML UI based call to addItem works and the UI updates to reflect the new data.
<table>
<tr>
<td>Status: </td>
<td><input type="text" ng-model="item.status" /></td>
</tr>
<tr>
<td>Priority Summary: </td>
<td><input type="text" ng-model="item.priority_summary" /></td>
</tr>
<tr>
<td colspan="2"><input type="Button" value="Add" ng-click="addItem(item)" /> </td>
</tr>
</table>
<div ng-repeat="item in items">
<p class="priority">{{item.priority_summary}}</p>
<p class="type">{{item.type}}</p>
</div>
Here is the JavaScript
var app = angular.module('DemoApp', []);
<!-- Define controller -->
var contrl = app.controller("MainController", function ($scope) {
$scope.items = [{
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}];
$scope.addItem = function(item)
{
alert("addItem called");
$scope.items.push(item);
$scope.item = {};
}
$scope.subscribe = function(){
//Code for connecting to the endpoint...
alert("event received"); //We receive this alert, so event is received correctly.
//***This code (items.push(item) is not working
//and we do not get the UI updated to show the newly added item.
/*Commented - NON WORKING
item.status = "New";
item.priority_summary = "High";
$scope.items.push(item);
// $scope.$apply();
});*/
//Working Code....
$scope.items.push({
status: 'New',
priority_summary: 'H'
});
$scope.$apply();
}
//calling subscribe on controller initialization...
$scope.subscribe();
However, I am having trouble understanding how can I add a new item programmatically and see those changes on the UI.
Essentially, the subscribe() function in the code snippet is listening for external events and needs to insert an item in the list programmatically / update the UI, is not working.
I have been looking for a while and tried various examples from SO and elsewhere, but I cannot get it to work for this rather simple looking case. Any pointers or guidance will be appreciated.
Thanks!
Updated in the question above...but figured I should mention the erring code and the working version here....
//NON WORKING CODE
//***This code (items.push(item) is not working
//and we do not get the UI updated to show the newly added item.
item.status = "New";
item.priority_summary = "High";
$scope.items.push(item);
// $scope.$apply();
});
//Working Code....
$scope.items.push({
status: 'New',
priority_summary: 'H'
});
$scope.$apply();
No need to pass newItem from HTML to controller since newItem is a $scope variable and controller already has access to it.
Here is the working code:
<!-- html -->
<div ng-controller="MyController">
<table>
<tr>
<td>Status: </td>
<td><input type="text" ng-model="newItem.status" /></td>
</tr>
<tr>
<td>Priority Summary: </td>
<td><input type="text" ng-model="newItem.priority_summary" /></td>
</tr>
<tr>
<td colspan="2"><input type="Button" value="Add" ng-click="addItem()" /> </td>
</tr>
</table>
<div ng-repeat="item in items">
<p class="priority">{{item.priority_summary}}</p>
<p class="type">{{item.status}}</p>
</div>
</div>
<!-- js -->
.controller('MyController', ['$scope', function($scope) {
$scope.items = [{
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}];
$scope.newItem = {};
$scope.addItem = function(){
$scope.items.push($scope.newItem);
$scope.newItem = {};
}
}]);

Categories

Resources