Changing an Angular ng-model with jQuery - javascript

I'm writing a Google Chrome extension which will interact directly with an AngularJS app.
Data is passed into Chrome's localstorage (chrome.storage.local) in one page, and then retrieved when the user loads my app's page.
The Angular is basically just a form with ng-models attached, like so:
<input id="q1" ng-model="inputName" >
<input id="q2" ng-model="inputTitle" >
<input id="q3" ng-model="inputAge" >
<button ng-click='submit()' >
The submit() function saves the ng-model values to my database to be retrieved later.
There are similar questions here which use older versions of AngularJS and I cannot get to work with Angular 1.2+ (I'm on Angular 1.2.2).
I've tried:
$('#q1').val(obj.title).trigger('input');
I've also tried:
$('#q1').val(obj.title);
angular.element($('#q1')).triggerHandler('input');
Neither work, in fact the latter makes no value change occur at all. What's the fix?
EDIT: Here's the Angular function being called on click, if there's something I can do in here to force ng-model to check the html input's value (that was set by jQuery in the Google Chrome extension) then that could be a solution:
$scope.submit = function(){
var theEvent = {
inputTitle: $scope.inputTitle,
inputName: $scope.inputName,
inputAge: $scope.inputAge
};
$rootScope.existing = theEvent;
$http({
url: '/api/saveToMongo/newEvent',
method: "POST",
data: theEvent
}).
success(function(data, status, headers, config) {
$cookies.oldSession = data;
$location.path('/collect');
}).
error(function(data, status, headers, config) {
console.log("There was an error submitting!");
});
};
All of these are returning null when I submit to my database, although if I type in the values manually then they work fine.

Related

AngularJS and serverside filter and pagination

I'm looking to use Angular JS with WebAPI - will be returning a large number of results from the WebAPI and so want to use some sort of server-side pagination and filtering.
Most of the tutorials i've seen are for client side filtering which isn't what i'm looking for.
Not really used AngularJS before, so looking for a simple example which can show how to utilise this - effectively i have a list of products and want to be able to for example filter by price. As it's a large data set i'd want to utilise pagination as well.
At the moment, in my controller I have:
app.controller("MyController", function ($scope, $http){
$http.get('/api/ProductResults').
success(function (data, status, headers, config) {
$scope.results = data.results;
}).
error(function (data, status, headers, config) {
// log error
});
which will return a list of products and i will use to output a list.
The WebAPI will take parameters for page number and filters etc. but i'm not sure how to implement this in the code.
$http.get('/api/Products?page=1&minPrice=10')
I'd expect that i would get the current page number and min price from the URL parameters?
For the page number and minPrice, you could have scope variables that hold that info for you. Let's say you have a data grid on the page that includes navigation for the several pages of data you have. In this case, I would have a $scope.pageNumber variable bound to that data grid navigation item. A click on next or previous changes the value of $scope.pageNumber and on you $http you would use that $scope.pageNumber when constructing your request URL. The same goes for minPrice.
You can add your parameters to your request like this:
$http({
url: "/api/Products",
method: "GET",
params: {page : 1, minPrice : 10}
});

angular-input-modified - setting form prestine

I am using an angular form which edits data. The data is fetched by $http and assigned to a controller object. I see that the form is set to modified due to this data assignment. I would like to have form state as not modified. This is being done on a button click, i would rather do it $http.success. this does not seem to be working though. Can you please advice?
Thanks
I had the same problem and I did the delayed initialization as shown at http://betsol.github.io/angular-input-modified/delayed-init/
Here is my code.
$http({
...
...
}).success(function(rdata, status, headers, config) {
$scope.user = angular.copy(rdata.data);
// Calling set-pristine after digest cycle.
if ($scope.myProfileForm) {
$timeout(function() {
$scope.myProfileForm.$setPristine();
});
}
}).error(function(data, status, headers, config) {
...
...
});

AngularJS ngKeyUp function the value is undefined

html
<input class="input--style" type="email" name="email" ng-model="attempt.email" ng-keyup="check(attempt.email)" value="">
angularjs
$scope.check = function(text){
console.log(text);
$http({
method: 'POST',
url: '/api/user/check/',
data: {'email': $scope.attempt.email},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data, status, headers, config) {
console.log(data);
$scope.user.emailvalid = data.email;
});
}
This input is inside a modal and when the modal fires the angular above is inside that modals controller, it works as expected but when I start typing in the input field the console.log(text); outputs undefined
$scope.attempt = {} this is before my angular script above and I'm just curious as to why this isn't working.
Do you really want to make a call to the server every time that the user presses a key? Wouldn't you prefer to have a debounce of at least ~200ms?
Try doing this instead:
<input class="input--style" type="email" name="email"
ng-model="attempt.email" ng-model-options="{ debounce: 200 }"
ng-change="check(attempt.email)" >
Update:
I forgot to answer your original question: you are using an input type="email", so unless it's a valid email angular will set the model to undefined. Therefore, angular is actually doing you a favor, because you probably don't want to make that call to the server unless the model contains a valid email address, right? So, just change your 'check' function so that it first checks if the value is undefined , and if it is don't make the call to the server and set $scope.user.emailvalid to false.

Angular.js: URL validation always returns 200

I got a website (Angular.js based) with an online form where users may enter any URL. I would like to instantly check out of the browser, whether the entered domain is valid (=reachable, can be connected to). I therefore only need the header information (status code), NOT the actual website content. I tried this piece of code, but it keeps returning code 200, no matter what the address is:
$scope.checkURL = function(index){
if($scope.items[index].address != ""){
$http({
method: 'GET',
url: $scope.items[index].address
})
.success(function(data, status, headers, config){
if(status){
alert('yes!!'+status.toString()); //<--- always getting this!!!!
}
})
.error(function(data, status, headers, config){
if(status){
alert('error!!'+status.toString());
}
});
}
};
I am aware that I am running into CORS-issues here. I just wanted to ask if:
There is any way to reliably (!) perform this kind of URL-checking out of the browser (again, I just need header/status information, not any actual website content) - preferably using AngularJs.
Unless anyone tells me otherwise, I'd alternatively set up a REST-service on my node.js webserver that I query every time, although I wanted to keep that load away from my server. Any suggestions?

Angular JS from rs.send()

Im generating some html code with angular in it, lets say it look something like this
exports.someApi = function(req,res){
res.send('<p>some html {{ "ENTER-PASSWORD" | translate }} </p>');
}
and in my controller im doing this
$http({method: 'GET', url: '/someapi'}).
success(function(data, status, headers, config) {
console.log(data);
$('.testPrint').html(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
the problem is, I get resposne rigth, but angular code is not executed it print this in html
some html {{ "ENTER-PASSWORD" | translate }}
it should write some html enter password
How to do this?
This is not the way to go with Angular. Specifically, $(...).html(data) will set the data directly to DOM, bypassing Angular's compilation step. This step is where the "magic" happens" (i.e. in your case the {{...}} get bound to the model).
Some ways to do it:
Make a directive and use templateUrl: "/someapi". When the directive is to be displayed, Angular will load /someApi and compile it.
Use ng-include="'/someApi'" (note single quotes within double quotes; this is intentional). Maybe together with ng-if to hide the content when not wanted.
The ui-router provides advanced facilities for subview navigation that may suit your needs.
A must-read is this great answer.

Categories