I'm new to Angular JS and I've been learning from codeschool.
I have this problem i can't figure out how to solve: I want to get data from a PHP file that I'm working on but first I wanted to make a short example because something just doesn't make sense to me, and is that can never retrieve the information that has the PHP file to the angular controller.
I have uploaded it on a jsfiddle you can check out if you want.
Here's the html, it's pretty basic:
<div ng-app="app">
<div ng-controller="MyController as c">
<h1>{{c.title}}</h1>
<p>Controller trial: {{c.content}}</p>
</div>
</div>
And here the JavaScript source:
var app = angular.module("app", []);
app.controller("MyController", ['$http', function ($http) {
this.title = "My Title";
var filecontent = "Data should be replaced";
$http.get("http://www.otherwise-studios.com/example.php")
.success(function (data) {
filecontent = data;
//I don't know why data is not loaded here :S
});
this.content = filecontent;
}]);
Finally, this is the output i'm getting:
My Title
Controller trial: Data should be replaced
If you visit the link from which i'm retrieving the information you should see this output "You connected to my PHP file", but as i said before, the data seems to never get updated to the variable:
this.content
Thank you so much for all your help!
Juan Camilo Guarin P
Data isn't loaded here, because initially "content" is primitive.
You have two ways: init "content" as object or write smth like this:
var filecontent = "la la la",
that = this;
$http.get("http://www.otherwise-studios.com/example.php")
.success(function (data) {
that.content = data;
});
app.controller("MyController", ['$http', '$scope' function ($http,$scope) {
this.title = "My Title";
var filecontent = "Data should be replaced";
$http.get("http://www.otherwise-studios.com/example.php")
.success(function (data) {
filecontent = data;
$scope.content = filecontent; // must be within success function to automatically call $apply
});
}]);
Related
I am just getting started with AngularJS. I'm coming from backend development, so this JavaScript is confusing for me. I followed the AngularJS tutorial and got the basics working.
I have a "record-list.component.js" file (Name derived from the AngularJS demo) which has a function to download data:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
})
This all works fine. However, I want to add another function that will call a URL so the backend can perform some magic. So I tried something like this:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://blackvue.tozz.nl/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
function DownloadFileController($file) {
$window.alert("Hi: " + $file);
}
})
This does not work. I tried a variety, such as controller: function, but nothing seems to work. Can someone point me into the good direction?
#Luiz Carlos his answer was correct! I got it working with the following code:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
this.DownloadFileController = function ($file) {
window.alert("Hi!");
}
}
})
And in HTML I can do:
<button ng-click="$ctrl.DownloadFileController()">Test</button>
Thanks!
I am calling a Web Service which returns around 3000 records as data entries as HTML response & i am trying to read this response using angularJS.
Below is my AngularJS code i am using to call the service
angular.module('tabApp', ['ngSanitize'])
.controller('TabController', ['$scope', 'HttpService', function($scope, HttpService) {
$scope.tab = 0;
$scope.setTab = function(newTab){
$scope.tab = newTab;
$scope.loading = true;
HttpService.CallService('Service.php?id='+newTab,newTab, function (data) {
$scope.myText = data;
$('.count').show();
$("[id^=searchg]").show();
$('.results').show();
});
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
$scope.setTab1 = function(newTab1){
$scope.tab = newTab1;
$('.loaderImage').hide();
};
$scope.isSet1 = function(tabNum){
return $scope.tab === tabNum;
};
}])
.service('HttpService', ['$rootScope', '$http', function ($rootScope, $http) {
$rootScope.loading = true;
return {
CallService: function (url,tabnum, callback) {
$http({
method: "POST",
url: url,
data: {id: tabnum}})
.success(function (data, status) {
$('.loaderImage').hide();
callback(data, status);
}).error(function (data, status) {
$('.loaderImage').hide();
callback(status);
});
}
}
}]);
My problem is the browser hangs if the returned records are more than 1500. Please advise on how i can improve this.
Update:
My html code looks like this
<div ng-show="isSet(1)">
<div id=matches style="display:none"></div>
<input type=text id=searchg placeholder="Type to search..." style="display:none" />
<p class="preload" ng-bind-html="myText"></p>
</div>
As we can see it is the bulky data which you are trying to bind. In Future, it could be more bulky.
You should use the server side pagination and get only the number of records, what your pagination is.
Here is the JSFiddle link for the reference.
http://jsfiddle.net/dwahlin/3Kewg/
Hope this helps! CHEERS TO CODE! :)
As #Mohit Dixit suggested, you should prefer to do server side paging and request only active page records.
I would advise you to use smart table library for this. Here is the official website for same. They support paging(both server side and client side), filter and sorting in one go.
Please note that there are many library available for this purpose but I am suggesting this as I am using it from past few years.
$scope.pause = function(userid){
var id = $scope.userid;
var status = 3;
getClients.status(id,status).then(function(response)
{
console.log('Response',response);
$scope.clients = response.data;
console.log('Data',$scope.clients);
$scope.cancel();
});
};
I am updating this in view file by clicking it and want to show in view file without refreshing it.
Solution,
HTML
<div ng-controller="controllerName" ng-int="getData()">
</div>
JS
app.controller("name",fucntion(){
$scope.getData = function(){
//api call to get data from database
$scope.data = resultData;
}
$scope.yourEditFunction = function(){
//make API call to update data in database
$scope.getData();
}
})
But ideally if you assign your get API result to an $scope variable and later in edit function update it then there is no need to refresh page angular will update the data for you.
I am using angularjs and springmvc in the application. My requirement is to hit the webpage(URL) and whatever response it returns(basically it returns html content of the webpage accessed through URL) i need to show on the html page.
Below is my code:
one.html
<div class="myDiv">
<table style="width:100%;height:100%;">
<tr>
<td ng-controller="getHTMLController">
<h1>HIT the URL and get the response</h1>
</td>
</tr>
</table>
{{htmlResponsedata}}
</div>
JavaScript
myApp
.controller("getHtmlDataController", [
"$scope", 'MyService',
function ($scope, MyService) {
MyService.fetch().then(function (response) {
$scope.htmlResponsedata = response;
}, function (errResponse) {
$scope.cancelModal();
$rootScope.showError(500, "Internal error");
});
_myServiceFactory.fetch = function () {
var deferred = $q.defer();
var repUrl = myAppURL + '/percentValues/' + '/getHtmlData.form';
$http.get(repUrl).then(function (response) {
console.log("response");
derred.resolve(response.data);
},
function (errResponse) {
console.error('Error while fetching data');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}
]);
Java
#RequestMapping(value = "/getHtmlData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String getHtmlData() throws Exception {
URL url = new URL("https://xyz/abc.com/values/reports");
HttpsURLConnection connection = ((HttpsURLConnection) url.openConnection());
connection.addRequestProperty("User-Agent", "Mozilla/4.0");
InputStream input;
input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String msg;
while ((msg = reader.readLine()) != null)
System.out.println("--------------------"+msg);
return msg; //html code of the URL
}
}
Above is my entire code written using angularjs and springMVC. How to print the data returned by msg from java code on the oe.html page.I have used {{htmlResponsedata}} but the response is not printed. htmlResponsedata is the response i got and which i have set $scope.htmlResponsedata = response in the js code as shown above. Any suggestions as how to print the html response back on the screen?
In stages, I setup my .Net MVC solution and ensured both Angular JS and KendoUI are working independently.
app.js:
var app = angular.module("app", ['kendo.directives']);
and in my controller, I have the following defined:
app.controller('contentTypesController', ['$scope', '$log', 'contentTypesRepository',
function ($scope, $log, contentTypesRepository) {
var a = {};
$scope.status;
$scope.contentTypes;
$scope.contentTypeOptions;
// for testing purposes, but not used - used for navigation properties
$scope.users;
getContentTypes();
function getContentTypes() {
// call the data repository
contentTypesRepository.getList()
.success(function (contentTypes) {
//console.log(contentTypes.value[0].Description);
//$log.log(contentTypes.value[0].Description)
$scope.contentTypes = contentTypes;
$scope.contentTypeOptions = {
dataSource: {
data: contentTypes
},
dataTextField: "Description",
dataValueField: "ContentTypeId",
optionLabel: "Select a Content Type"
};
})
.error(function (error) {
$scope.status = 'Unable to load data: ' + error.message;
});
}
$scope.updateContentTypes = function (id) {
var contentType;
for (var i = 0; i < $scope.contentTypes.length; i++) {
var currentType = $scope.contentTypes[i];
if (currentType.ID === id) {
contentType = currentType;
break;
}
}
};
$scope.insertContentType = function () {
// get contentType description from the client
var contentType = { 'Description': $scope.newContentType };
contentTypesRepository.insert(contentType)
.success(function () {
$scope.status = 'Added new content type. Refreshing list.';
// add the new content type to the client-side collection
$scope.contentTypes.value.push(
{ 'Description': $scope.newContentType }
);
$scope.newContentType = "";
})
.error(function (error) {
$scope.status = 'Unable to insert new content type: ' + error.message;
});
};
$scope.deleteContentType = function(id) {
contentTypesRepository.remove(id)
.success(function () {
$scope.status = 'Deleted content type. Refreshing list.';
for (var i = 0; i < $scope.contentTypes.length; i++) {
var contentType = $scope.contentTypes[i];
if (contentType.ID === id) {
// remove the content type from the client-side collection
$scope.contentTypes.splice(i, 1);
break;
}
}
// navigation properties = null
// $scope.xxxx = null;
})
.error(function (error) {
$scope.status = 'Unable to delete content type: ' + error.message;
});
};
// get some navigation property
//$scope.getCustomerOrders = function (id) {
// dataFactory.getOrders(id)
// .success(function (orders) {
// $scope.status = 'Retrieved orders!';
// $scope.orders = orders;
// })
// .error(function (error) {
// $scope.status = 'Error retrieving customers! ' + error.message;
// });
//};
$scope.addContentType = function () {
//return $scope.newContentType.$save();
$scope.contentTypes.value.push(
{ 'Description': $scope.newContentType }
);
$scope.newContentType = "";
}
In following the Angluar/Kendo examples here, I added code related to $scope.contentTypeOptions.
In my view:
<select kendo-drop-down-list k-options="contentTypeOptions"></select>
Which displays a dropdown, but no data.
I am able to view the data in a ng-repeater:
<ul>
<li ng-repeat="contentType in contentTypes.value">
{{ contentType.Description }}
</li>
</ul>
And the raw data by {{ contentTypeOptions }}.
Since the repeater uses contentTypes.value, I tried this as well in
$scope.contentTypeOptions = {
dataSource: {
data: contentTypes.value // tried both contentTypes and contentTypes.value
},
dataTextField: "Description",
dataValueField: "ContentTypeId",
optionLabel: "Select a Content Type"
};
... which is based on the JSON data:
Ultimately, I would like to get all the CRUD hooked up for a grid (which I have done in the past with OData, but now adding AngularJS to the mix) and thought simply displaying the data in an Angular/Kendo mix would be a good start. I'm hoping that after getting this pinned down the rest will be simple, and appreciate any suggestions.
Your code is a bit confusing since methods like $scope.updateContentTypes treat $scope.contentTypes as an array, but at the same time contentTypes appears to be an object with a property value which is an array.
One thing to be aware of is that Kendo UI widgets will convert your array to a Kendo DataSource internally. This means that changes you make to $scope.contentTypes won't affect the items in your data source in $scope.contentTypeOptions.
Another issue is that there is no full two-way binding between widgets and the data source in angular-kendo, and until recently, the data source wouldn't update at all unless you specifically declared it as a DataSource. There have been some improvements lately, although it's still not fully integrated, as far as I can see.
(you can try creating a deep watch on the data yourself, but that may create performance problems; see related post here).
Your dropdown doesn't show the data because you replace $scope.contentTypeOptions after creating the widget, and there is no $watch on that property that would update the widget with these options.
You can either create a DataSource explicitly and update that with:
$scope.contentTypeOptions.dataSource.data(contentType.value);
or you can use the attribute:
k-data-source="contentTypes"
which will create a $watch on $scope.contentTypes, so when you replace it, the widget will update as well.
Maybe this basic (although admittedly a bit messy) example will help you somewhat (I set up the 2nd dropdown in the same way you did; the "change" button updates the data source).
You will need to use the Angular Kendo bindings from Kendo labs.
Here is a an article with live demo and full source code:
http://blog.longle.io/2014/05/01/angularjs-kendo-ui-using-angular-kendo-with-asp-net-mvc-5-web-api-odata