My Angular view is not updated with data form server - javascript

I am using Angularjs and i make a call form server to retrieve data. Data are successfully retrieved but my view is not updated. I don't understand why. Here are the code i use.
Angularjs and html code :
<div class="row custom-margin" ng-controller="ListCtlr" ng-init="initData()">
<form class="form-inline" role="form" id="formId" name="formId">
<div class="form-group">
<label for="searchInput">Data to search</label>
<input ng-model="searchInput" placeholder="Enter term to search">
</div>
<button type="submitSearch" class="btn btn-primary" ng-click="search()">Go</button>
</form>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr class="info">
<th colspan="4" class="centertext">Name</th>
<th colspan="3" class="centertext">Age</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<td>{{person.name}}</td>
<td>{{person.age}}</td>
</tr>
</tbody>
</table>
</div>
</div>
Controller code :
function ListCtlr($scope, $http, $location,$filter) {
$scope.formId = {searchInput: ''};
$scope.search = function () {
var url='server/search/'+this.searchInput;
$http.get(url)
.success(function (data) {
$scope.persons = data;
})
.error(function(data){
$scope.error = data;
});
};
}
When i inspect the data retrieved form server i get the following JSON data :
[{"name":"John","age":12},{"name":"Mary","age":25},{"name":"Garry","age":28}]
What's missing please ?

Change
<tr ng:repeat="person in persons">
<td>{{person.name}}</td>
<td>{{person.age}}</td>
</tr>
to
<tr ng-repeat="person in persons">
<td>{{person.name}}</td>
<td>{{person.age}}</td>
</tr>

The problem is that your ListCtlr controller is placed on a div that does not contain your ng-repeat.
To solve this, create an outer div, put the ng-controller on that div:
<div ng-controller="ListCtlr">
... (place contents of your html here) ...
</div>
This ensures that ListCtlr's scope includes the ng-repeat.
Note: Be sure to remove the ng-controller="ListCtlr" defined in your inner div.

Related

How do I add a row dynamically using angular js in a table?

How do I add a row dynamically using AngularJS in a table, which contains data from a get request?
I have written a code as such:
<table id="tableRow" class="table table-bordered tableRow">
<thead>
<tr>
<th></th>
<th>
<label>Make</label>
</th>
<th>
<label>Vin</label>
</th>
<th>
<label>Model</label>
</th>
<th>
<label>Parts</label>
</th>
<th>
<label></label>
</th>
<th>
<label></label>
</th>
</tr>
<thead>
</table>
now using angular js how can i add a row on click of a button or a get request in the same table...?
i had written a script which did'nt work the script is as follows..
$scope.myGet = function() {
$http.get("http://172.17.133.82:8080/restproj/v1/dealer")
.then(function(response) {
$scope.addRow = response.data;
var tall = '';
tall += '<tr>'+
'<td><button class="btn btn-danger btn-remove" type="button"><i class="glyphicon glyphicon-trash gs"></i></button</td>' +
'<td><input type="text" class="form-control" id="makeid" ng-model="addRow.make"></td>' +
'<td><input type="text" class="form-control" id="vinid" ng-model="addRow.vin"></td>'+
'<td><input type="text" class="form-control" id="modalid" ng-model="addRow.model"></td>' +
'<td ng-repeat="part in addRow.parts"><input type="text" class="form-control" id="partsid" ng-model="addRow.name"><input type="text" class="form-control" id="partsid" ng-model="addRow.desc"></td>' +
'</tr>';
$('#tableROW').append(tall);
});
I get error such as :
tabelform.html:320 Uncaught SyntaxError: Unexpected end of input
angular.min1.5.9.js:6 Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.5.9/$injector/modulerr?p0=myApp&p1=Error%3A%2…Ic%20(http%3A%2F%2F127.0.0.1%3A63139%2Fjs%2Fangular.min1.5.9.js%3A21%3A332)(…)
You probably want to bind your table to a backing list and use ng-repeat to build up your table dynamically:
<div ng-app="myApp" ng-controller="carCtrl">
<table>
<tr ng-repeat="car in cars">
<td>{{ car.make }}</td>
<td>{{ car.vin }}</td>
<td>{{ car.model }}</td>
</tr>
</table>
</div>
Your corresponding Angular script would look something like:
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://172.17.133.82:8080/restproj/v1/dealer")
.then(function (response) {
$scope.cars = response.data.records;
});
});
</script>
Or if you want to add cars whenever you get an ajax response you could push them to a list (or concat the existing list, or whatever fits your case)
$scope.cars.push(response.data.records)
Angular has 2-way data binding, so if it sees that the backing list changed (e.g. by adding extra cars in the list), it will update your table dynamically.
I have created A JS Fiddle For This please Refer it
Refer This Example
In JS
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest()
}).success(function(data, status) {
$scope.people= $scope.people.concat(data);
});
In HTML
<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
<p> Click <a ng-click="loadPeople()">here</a> to load more data.</p>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="person in people">
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</table>
</div>
</div>

Angularjs not working after html is added with ajax

My issue is when I load the page first time the angular is working pretty well. but when I try to use same thing when my html is loaded with ajax it is not working at all. nor I can see any relevant error in console.
javascript:
var myApp = angular.module('myApp', ['ngSanitize','ui.utils']);
myApp.controller('CtrlPerformanceByTrack', function($scope, $http) {
$http.get(site_url + 'performance/?method=get_performance_by_track_data').success(function(data, status) {
/*console.log(data.data);
data=[{"title":"title 1","length":"3:02","plays":4,"sales":2,"likes":8},
{"title":"title 1","length":"3:02","plays":4,"sales":2,"likes":8}]
console.log(data);*/
$scope.tracks = data.data;
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
});
html:
<div data-ele="PerformanceByTrackApp" class="track-block" ng-controller="CtrlPerformanceByTrack">
<div class="title">
Performance by track
</div>
<div class="search-block">
<form>
<div class="content fr">
<div class="left-input">
<input type="text" class="form-control" placeholder="Search Track" ng-model="searchTrack">
</div>
<div class="right-icon-block">
<span class="icon-magnifying42 search-icon"></span>
</div>
</div>
</form>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
<div class="table-block">
<table class="table table-striped table-responsive track-table">
<thead class="title">
<th style="width:50%;">Title</th>
<th style="width:13%;">Length</th>
<th style="width:13%;">Plays</th>
<th style="width:13%;">Sales</th>
<th style="width:14%;">Likes</th>
</thead>
<tr ng-repeat="item in tracks | filter:searchTrack">
<td>{{item.title}}</td>
<td>{{item.length}}</td>
<td>{{item.plays}}</td>
<td>{{item.sales}}</td>
<td>{{item.likes}}</td>
</tr>
</table>
</div>
</div>
the sample is at below url:
http://engagev2.ncryptedprojects.com/performance
to call the same page via ajax click performance tab at left.
If you're getting this partial HTML via AJAX, then it should be properly inserted. You have to use angular $compile service. Simplified example below.
...
var template = getTemplate();
var compiledElement = $compile(template)($scope);
element.append(compiledElement);
...
Here is the link https://docs.angularjs.org/api/ng/service/$compile

How can I change the innerHTML of div with a variable, inside the scope function in angular js?

I have 2 HTML pages. In my index.html page you can see products information that comes from JSON file. I need to have detail of product in detail.html page when people click on particular product. Alert can show the details but unfortunately the innerHTML of my <p> does not change, please guide me.
<div ng-app="myApp" ng-controller="AppController">
<div id="serachWrapper">
<h1 id="headerTopic">Our Products</h1>
<input id="searchInput" name="search" type="text" placeholder="Search products" ng-model="searchquery"/>
<table id="searchTable">
<thead id="tbHead">
<tr class="tbRow">
<th class="tbTopics">ID</th>
<th class="tbTopics">Name</th>
<th class="tbTopics">Color</th>
<th class="tbTopics">Type</th>
<th class="tbTopics">Capacity</th>
<th class="tbTopics">Price</th>
</tr>
</thead>
<tbody id="tbBody">
<tr class="tbRow" ng-repeat="x in myData | filter:searchquery ">
<td class="tbcontents" >{{x.id}}</td>
<td class="tbcontents">{{x.name}}</td>
<td class="tbcontents">{{x.color}}</td>
<td class="tbcontents">{{x.type}}</td>
<td class="tbcontents">{{x.capacity}}</td>
<td class="tbcontents">{{x.price}}</td>
</tr>
</tbody>
</table>
</div>
And this is my Angular js code:
var app = angular.module('myApp', ['ngSanitize']);
app.controller('AppController', AppController);
function AppController($scope , $http) {
$http.get("products.json").success(function(myData){
$scope.myData = myData;
$scope.go = function(item){
var detail = item.detail;
var productDetail = angular.element(document.getElementById('product-detail')).html();
productDetail = detail;
alert(detail)
};
});
}
You can keep both codes in the page and to solve this with an ng-if directive
Angular ng-if directive
<body ng-app="ngAnimate">
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
This is removed when the checkbox is unchecked.
</span>
</body>
Why is your $scope.go function defined inside the http.get request?
Try:
function AppController($scope , $http) {
$http.get("products.json").success(function(myData){
$scope.myData = myData;
});
$scope.go = function(item) {
var detail = item.detail;
var productDetail = angular.element(document.getElementById('product-detail')).html();
productDetail = detail;
alert(detail)
};
}

Angularjs ng-repeat to repeat depending on a variable in the controller

This is a partial view. Ng-repeat repeats over a json file that contains 50 email records.
<table class="table table-hover" ng-controller="emailViewController">
<tbody data-ng-controller="settingsController">
<tr ng-repeat="email in emails" >
<td><input type="checkbox" ng-checked="checkAllEmail" ng-model="selectedEmail"/>
<a href="#">
<span class="glyphicon glyphicon-star-empty"></span>
</a></td>
<td><label ng-bind="email.from"></label></td>
<td><label ng-bind="email.subject"></label></td>
<td><label ng-bind="email.time"></label></td>
</tr>
</tbody>
</table>
settingsController.js
(function() {
'use strict';
var settingController = function (fetchDataService, $scope, savePreferenceService, $localStorage) {
$scope.url = 'app/mock/settings.json';
$scope.save = {};
fetchDataService.getContent($scope.url)
.then(function(response){
$scope.contacts = response.data.contacts;
$scope.languages = response.data.languages;
$scope.conversations = response.data.conversations;
$scope.undoSend = response.data.undoSend;
$scope.save = response.data.userPreferences;
});
$scope.setPreference = function () {
savePreferenceService.setPreferences($scope.save.selectedLang, $scope.save.converse, $scope.save.selectedNumber, $scope.save.selectedNumberContact, $scope.save.reply, $scope.save.signature);
}
$scope.conversation = $localStorage.selectedNumber;
};
angular.module('iisEmail')
.controller ('settingsController',
['fetchDataService', '$scope', 'savePreferenceService', '$localStorage', settingController]);
}());
I am having trouble figuring out how to get ng-repeat to iterate the JSON file depending on the value of $scope.conversation. So, for example, if $scope.conversation is 10, I want ng-repeat to iterate only 10 times. I don't want to display the remaining 40 emails. Does anyone have any ideas on how to achieve this functionality?
UPDATE
With the help of #Prashank's comment, I figured it out. Here is the code using the limitTo filter.
<table class="table table-hover" ng-controller="emailViewController">
<tbody data-ng-controller="settingsController">
<tr ng-repeat="email in emails | limitTo: conversation" >
<td><input type="checkbox" ng-checked="checkAllEmail" ng-model="selectedEmail"/>
<a href="#">
<span class="glyphicon glyphicon-star-empty"></span>
</a></td>
<td><label ng-bind="email.from"></label></td>
<td><label ng-bind="email.subject"></label></td>
<td><label ng-bind="email.time"></label></td>
</tr>
</tbody>
</table>
You can use limitTo or slice and do the following,
here is a sample,
Using limitTo:
<div ng-repeat="item in items | limitTo:needed">
{{item.name}}
</div>
limitTo
Well there are two ways of doing this.
The easier way would be to use $index in your ng-repeat to hide/show the items as follows:
<tr ng-repeat="email in emails" ng-hide="conversation.length() < $index">
//same as in the question
</tr>
The way I would do it(although its a little lengthy) is using a filter as follows:
HTML:
<tr ng-repeat="email in emails | conversationFilter: conversation">
//same as in the question
</tr>
Filter:
app.filter('conversationFilter', function() {
return function(collection, conversation) {
return collection.slice(0, conversation);
}
})

Check if value insert exist in dropdown with angularjs

I have a input with an autocomplete with angularjs. This autocomplete is from a json that is represented by a table in a dropdown. I can filter the results and click the correct value but i would check if the user type some value that is not in the dropdown with an error message. Here is the code:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div class="uk-form-row uk-width-1-1" data-ng-repeat="items in inputList.getinputList">
<input ng-model='item.value' type="text" placeholder="Choose"/>
<!-- WORKS OK -->
<div class="uk-parent" data-uk-dropdown="{mode:'click'}">
Nav item - Works OK
<div class="uk-dropdown uk-dropdown-navbar" style="top:50px">
<table>
<thead>
<tr>
<th>First Value</th>
<th>Second Value</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item in numberList.getList | filter:item.value" ng-click="setSelected(item)">
<td>{{item.first}}</td>
<td>{{item.last}}</td>
</tr>
</tbody>
</table>
</div>
</div>
The angularjs part
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.item={}
$scope.numberList={}
$scope.numberList.getList=[{'first':'Jon','last':'skeet'},{'first':'naeem','last':'shaikh'},{'first':'end','last':'game'}]
$scope.inputList={}
$scope.inputList.getinputList=[{'firstA':'AAA','lastB':'BBBB'}]
$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
$scope.idSelectedVote = idSelectedVote;
$scope.item.value=idSelectedVote.first+' '+idSelectedVote.last;
//alert(idSelectedVote);
};
}
I created a fiddle here:
http://jsfiddle.net/8y48q/22/
You can use
<tr ng-show="(numberList.getList | filter:item.value).length == 0">
<td>Nothing here!</td>
</tr>
Fiddle

Categories