I am trying to use breeze to do the same calls that work using angualar's $http. For some reason the $scope does not appear to work in the breeze callback.
Code:
<!DOCTYPE html>
<html ng-app="">
<head>
<meta name="viewport" content="width=device-width" />
<title>App</title>
</head>
<body ng-controller="TextController">
<div>
<p>{{textData1}}</p>
<p>{{textData2}}</p>
<ul>
<li ng-repeat="patient in patients">
<span>{{patient.FirstName}}</span>
</li>
</ul>
</div>
<script src="/scripts/jquery-1.8.2.js"></script>
<script src="/scripts/q.js"></script>
<script src="/scripts/breeze.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
function TextController($scope, $http){
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore", true);
var serviceName = "/api/breeze";
var manager = new breeze.EntityManager(serviceName);
var query = breeze.EntityQuery.from("Patients");
$scope.textData1 = "Waiting..";
$scope.textData2 = "Waiting..";
manager.executeQuery(query).
then(function (data) {
console.log(data);
$scope.textData1 = 'Breeze';
//$scope.patients = [];
//$scope.patients = data;
}).
fail(function(error) {
$scope.textData1 = error.message;
});
$http({ method: 'GET', url: '/api/patients' }).
success(function (data, status, headers, config) {
console.log(data);
$scope.textData2 = 'Angular';
//$scope.patients = [];
//$scope.patients = data;
}).
error(function (data, status, headers, config) {
});
}
</script>
</body>
</html>
In the above code both the angular $http call and the breeze calls return data as I print it to the console. When this is run only the textData2 binding updates to 'Angular' the textData1 binding does not update to 'Breeze'. I'm in the function as the console gets called but the binding does not update. The same thing happens if I try to bind the list of data the the 'patients' reference in the scope. I commented that out to show the simplest version of my problem.
Make sense? Thoughts?
Brian
Related
I am new to AngularJS and need to use AngularJs to render my MVC controller Json output. Below is my MVC Controller that output Json:
[HttpGet]
public JsonResult GetAllData()
{
int Count = 50;
return Json(Workflow.Teacher.GetTeachers(Count), JsonRequestBehavior.AllowGet);
}
My Angular Controller that calls the GetAllData Action method:
angular.module('myFormApp', [])
.controller('HomeController', function ($scope, $http, $location, $window) {
$scope.teacherModel = {};
$scope.message = '';
$scope.result = "color-default";
$scope.isViewLoading = false;
$scope.ListTeachers = null;
getallData();
//******=========Get All Teachers=========******
function getallData() {
$http({
method: 'GET',
url: '/Home/GetAllData'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.ListTeachers = response;
console.log($scope.ListTeachers);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!';
console.log($scope.message);
});
};
})
.config(function ($locationProvider) {
$locationProvider.html5Mode(true);
});
Further my MVC layout markup is bellow:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Teachers List</h2>
<div id="content" ng-controller="HomeController">
<span ng-show="isViewLoading" class="viewLoading">
<img src="~/Content/images/ng-loader.gif" /> loading...
</span>
<div ng-class="result">{{message}}</div>
<table class="table table-striped">
<tr ng-repeat="teacherModel in ListTeachers">
<td>{{teacherModel.TeacherNo}}</td>
<td>{{teacherModel.TeaFName}}</td>
<td>{{teacherModel.TeaSName}}</td>
</tr>
</table>
</div>
#section JavaScript{
<script src="~/Scripts/angular.js"></script>
<script src="~/ScriptsNg/HomeController.js"></script>
}
further to above my main layout's body tag also have ng-app
<body ng-app="myFormApp" >
I am using MVC version 5 with AngularJs v1.6.4.
On debugging I can confirm that it does call getallData() actionMethod and does return rows in Json. I am not getting any error but its not rendering the model values either.
Any suggestions would be appreciated.
use response.data to catch the data.
change
$scope.ListTeachers = response;
to this
$scope.ListTeachers = response.data;
You have a number of problems with this code. Firstly, by assigning
$scope.ListTeachers = null;
you are making it more complicated to work with this variable later. If you expect REST interface to return you an array, then it is fine to make initial assignment as an empty array.
$scope.ListTeachers = [];
It is important because you should not override this object when you get a new result back. Angular adds its own magic to objects it is bound to, and by overriding an object you destroy that magic.
How you should update the data is something like this this:
then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.ListTeachers.length = 0;
if( response && response.data){
response.data.forEach(function callback(currentValue)
{
$scope.ListTeachers.push(currentValue);
});
}
console.log($scope.ListTeachers);
}
I hope this helps.
Then callback response has several parameters like data , headers, status , statustext to check your request.
I am merely trying to populate an array from an $http request and display the results in a table. Using Firebug, it seems to me that the data is being retrieved properly. See pictures for results.
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('ContactsController', function ($scope, $http)
{ var self = this; //added after initial post.
this.contactList = [];
this.InitiateContactList = function(arrayContacts) //this.InitiateContactList doesn't work?
{ for(i = 0; i < arrayContacts.length; i++)
this.contactList.push(arrayContacts[i]);
};
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ if(angular.isArray(response.data))
{ //this.contactList = response.data; //is this working properly?
self.contactList = angular.fromJson(response.data);
//this.InitiateContactList(response.data);
}
}, function errorCallback(response) {
});
});
app.controller('ActionsController', function ($scope, $http)
{
});
</script>
</head>
<body ng-controller="ActionsController as ActCtrl">
<div ng-controller="ContactsController as ContactsCtrl">
<table
<tr><th Email</th>
<th>Name</th>
<th>Frequency</th></tr>
</table>
<div ng-repeat="Contact in ContactsCtrl.contactList">
<table >
<tr><td>{{Contact.Email}}</td><td>test name</td><td>{{Contact.Frequency}}</td></tr>
</table>
</div>
</div>
</body>
</html>
this.contactList = angular.fromJson(response.data); seems to be working. The DOM array is populated as expected, but the ng-repeat doesn't seem to be working. I've done this procedure a couple other times in other contexts and it has worked as expected. What am I missing?
Update: The Batarang extension in Chrome shows the following:
Is it normal to have the index 'Contact' showing like that?
In your ContactsController, do this
var self = this;
Now use self instead of all this in your controller:
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
self.contactList = angular.fromJson(response.data);
});
Hope that helps.
this.contactList = angular.fromJson(response.data);
In this instance, this refers to the function prototype of the anonymous callback function from the then() call. Be careful in Javascript when using the word this in many callbacks and such. Declare a variable, and assign the needed function prototype, and then reference that variable, instead of the reserved, ever-changing this keyword.
I'm trying to use long polling within an angularjs app. I have the long polling within a controller that is updating a scope variable that is referenced within the view.
When I step through the code the polling is occurring and the expected data is being returned but the view is never being updated.
longpolltest.js
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $timeout) {
$scope.value = 1;
function poll() {
var d = new Date();
var n = d.getTime();
$scope.value++;
$.ajax({
type: 'GET',
url: '/gs/async?millis=' + n,
contentType: "application/json; charset=utf-8",
async: true,
cache: false,
success: function(data) {
var obj = jQuery.parseJSON(data);
if (obj.type == 'ServerTime')
$scope.myTime = object.Data.Time;
setTimeout("poll()", 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus + " " + errorThrown);
setTimeout("poll()", 10000);
}
});
}
poll();
});
longpolltest.html
<!DOCTYPE html>
<html>
<head lang="en">
<!-- jQuery JavaScript -->
<script src="js/ext/jquery-1.12.0.min.js"></script>
<!-- angular library -->
<script src="js/ext/angular/angular.min.js"></script>
<script src="js/ext/angular/angular-route.min.js"></script>
<script src="js/longpolltest.js"></script>
<meta charset="UTF-8">
<title>Long poll test</title>
</head>
<body ng-app="myApp">
<div>
<div ng-controller="MyController">
<p>
Time: {{myTime}}
Poll#: {{value}}
</p>
</div>
</div>
</body>
Any ideas why the view would not be getting updated would greatly be appreciated.
Thanks in advance.
Some general advice:
don't use jquery http method. You should prefer $http angular service.
don't use timeout function.You should prefer $timeout angular service.
don't invoke http remote services inside your controller. You should create a dedicated service.
A further improvement can be to use the $interval service
The below code is executing/sending data on body load but i want to make it onclick like
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
$.each(data, function(k, ip) {
save_info = ip +","+location.hostname+",var1,var2";
/* save_info= ip +","+location.hostname+",var1,var2"; */
});
$(document).ready(function() {
var json_object = {"data": save_info};
$.ajax({
url: "http://www.example.com/test/data.php",
data: json_object,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$("#saved").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$("#saved").text("Failed to save data !");
}
});
})
});
</script>
</head>
<body>
<a href="#" onclick='getJSON()'> click here</a>
<!-- I want to make json send data when this click event happens, suggest how to write onclick here -->
</body>
</html>
Please also suggest me if there is any alternative way using jquery/javascript to record this user's IP address & hostname, I want to send them to a remote page as parameters where it'll be saved.
getJSON() is not a function in itself. You never declared the function.
Do this:
function getJSON() {
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
$.each(data, function(k, ip) {
save_info = ip +","+location.hostname+",var1,var2";
});
});
}
I have a django url : '127.0.0.1:8000/showsym' mapped to view returning json response
def get_symptoms(request):
bp=BodySubPart.objects.get(body_subpart="head")
data1=bp.symptoms.all()
data = serializers.serialize('json', data1)
return HttpResponse(data,mimetype='application/json')
now i am trying to parse this in ajx_form.html and code for that is :
<html>
<head>
<title>Hist</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
(function() {
$.get('127.0.0.1:8000/showsym/', function(data1) {
alert(data1);
});
});
</script>
</body>
</html>
but it is not giving me any output
the page is coming blank
please help me here somebody
It is because your code tries to get the url: /127.0.0.1:8000/showsym/
Change 127.0.0.1:8000/showsym/ to /showsym/.
I suggest you use $.getJSON and name urls, assuming the url name of /showsym is showsym:
$(document).ready(function() {
$.getJSON('{% url showsym %}', function(data, textStatus, jqXHR) {
alert(data);
})
})