Angular watch issue - javascript

It's the first time I'm using Angular's watch function and apparently I don't get it to work.
I have a service called apiService, which has a variable myFile. I am injecting the service into my controller and want to watch the apiService.myFile value for a change. Unfortunately the watch only gets called on opening the webpage, not when the apiService.myFile variable actually changes. Here is the code for the watch:
$scope.$watch(function(){return apiService.myFile}, function (newVal, oldVal, scope) {
console.log("service changed: "+newVal +" : "+oldVal+" : "+ scope);
});
Why isn't it being called when myFilechanges?
UPDATE 1:
this is how I update the value of apiService.myFile inside the service
ApiService.prototype.uploadFile = function(fileContent) {
$.ajax({
url: "/space_uploadFile/",
type: "POST",
dataType: "json",
data: {
fileContent: fileContent
},
contentType: "application/json",
cache: false,
timeout: 5000,
complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
this.myFile =data;
console.log("this.myFile: "+this.myFile);
console.log('process success');
},
error: function() {
console.log('process error');
},
});
};

I added this inside a plunkr (as you didn't) and this works for me:
Sidenote: next time create an example demonstrating your problem (plunkr) so we can eliminate the case of your problem (e.g. typo).
var app = angular.module('app', []);
app.controller('mainController', function($scope, apiService) {
$scope.changeValue = function() {
apiService.myFile += "!";
};
$scope.$watch(function(){return apiService.myFile}, function (newVal, oldVal, scope) {
console.log("service changed: "+newVal +" : "+oldVal+" : "+ scope);
$scope.someValue = newVal;
});
});
app.service('apiService', function() {
this.myFile = "Test";
});
And the corresponding HTML:
<body ng-controller="mainController">
<h1>Hello Plunker!</h1>
{{someValue}}
<button ng-click="changeValue()">Click</button>
</body>
https://plnkr.co/edit/DpDCulalK1pZ8J0ykh2Z?p=preview
BTW: The $watch part is a copy from your question and it simply works for me.
Edit: Apparantly the OP was using $.ajax to do ajax calls and the value was updated inside the succeshandler (outside the Angular context). So there was no digest cycle triggered here. To fix this you should use the $http service provided by angular (or work your way around it without).
var self = this;
self.$http.post("/space_uploadFile/",
{ fileContent: fileContent },
{
cache: false,
timeout: 5000
})
.then(function (data) {
self.myFile = data;
console.log("self.myFile: " + self.myFile);
console.log('process success');
},
function () {
console.log('process error');
});
Edit2: Apparantly the OP was also using this in the succeshandler to acces variable on the controller. This won't work, so I used the self pattern in the sample above to solve it.

I am used to this syntax:
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
where name is the name of your property - in this case myFile

Related

Why is my datasource not returning all my data in Angular grid application>?

Let me first preface this by saying...I'm a noob and have been pouring over documentation already but I have not found a resolution.
I have built a custom report in PowerSchool SIS using AngularJS to form my grid and am using JSON data to fill it. The problem I am currently having is the grid is only populating 100 items even though there are close to 200 record items.
This is my JS:
//Begin Module - Loads AngularJS
define(['angular', 'components/shared/index'], function(angular) {
var attApp = angular.module('attApp', ['powerSchoolModule']);
// var yearid = window.location.search.split("=")[1];
//Begin Controller
attApp.controller('attCtrl', ['$scope', 'getData', '$attrs', function($scope, getData, $attrs) {
$scope.curSchoolId = $attrs.ngCurSchoolId;
$scope.curYearId = $attrs.ngCurYearId;
loadingDialog();
$scope.attList = [];
//Sets definition of the var dataSource to pull PowerQueries
var dataSource = {
method: "POST",
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
data: {yearid},
dataType: "json",
pages:"50",
};
console.log(dataSource);
//Sets definition of the var dataSource to pull from JSON files
console.log('loading dataSource');
//var dataSource= {method: "GET", url: "attendancedata.json"};
getData.getAttData(dataSource).then(function(retData) {
if (!retData.record) {
alert('There was no data returned');
closeLoading();
} else {
console.log(retData);
if (!!retData.record[retData.record.length]) {
// retData.record.pop();
}
var i = retData.record.length;
while (i--) {
retData.record[i].attendance_date = new Date(retData.record[i].attendance_date) // Changes the text of the attendance date to a JS data
}
//Sets scope of attList and attName
$scope.attList = retData.record;
$scope.attName = retData.name;
console.log($scope.attList);
closeLoading();
}
});
}]); //End Controller
//Begins factory and invokes PowerQueries if available, error message will trigger if no data returned
attApp.factory('getData', function($http) {
return {
getAttData: function(dataSource) {
return $http(dataSource).then(function successCallback(response) {
return response.data;
},
function errorCallback(response) {
alert('There was an error returning data');
});
}
}
}); //End Factory
}); //End Module
We have confirmed there is nothing wrong with my datasource. I'm stuck and could use a guiding word. Any advice would be appreciated.
Try to hit the same endpoint using PostMan, maybe the API is not working.
Also I'm not sure if this url is valid:
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade"

Why is $scope not working in Angular 1.6.1?

Background
After following the AngularJS tutorial on codeSchool and reading some StackOverflow questions, I decided to start using $scope in order to avoid the hassle of having to define a var self = this; variable.
Problem
The problem is that $scope seems to not be binding anything and nothing works when I use it. I have no idea why, but if I use a var self = this; variable my code will work, even though in theory (according to what I know) $scope should do the same ...
Code
Let's say I have a page where I want to display a big list of numbers. Let's also say I have pagination, and that I want the default amount of Numbers per page to be 4. Let's also assume that after each request to the server, I set the amount of Numbers shown per page to 4 again.
app.js
/*global angular, $http*/
(function() {
var app = angular.module("myNumbers", []);
app.directive("numberFilter", function() {
return {
restrict: "E",
templateUrl: "number-filter.html",
controller: function($scope, $http) {
$scope.filter = {
itemsPerPage: 4
};
$scope.makeRequest = function(numberList) {
console.log("Received submit order");
$http({
method: 'GET',
url: 'https://myNumberServer.com/api/v1/getPrimes',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function successCallback(response) {
numberList= response.data.entries;
$scope.totalPages = response.data.totalPages;
$scope.filter = {itemsPerPage: 4};
console.log("success!");
}, function errorCallback(response) {
console.log('Error: ' + response);
});
};
},
controllerAs: "filterCtrl"
};
});
})();
number-filter.html
<form ng-submit="filterCtrl.makeRequest(myNumbers.numberList)">
<div >
<label for="items_per_page-input">Items per page</label>
<input type="number" id="items_per_page-input" ng-model="filterCtrl.filter.itemsPerPage">
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
There are two expected behaviors that should happen and don't:
When I click submit, I should see in the console "Received submit order" and I don't.
The input element should be initialized with 4 when I load the page.
Both of these behaviors will happen if I use the var self = this; trick and replace all mentions of $scope with self.
Questions:
Why is this not working? Am I missing some closure?
You are using controllerAs syntax so when you use that your model needs to be assigned to the controller object itself, not to $scope
Example
controller: function($scope, $http) {
var vm = this; // always store reference of "this"
// use that reference instead of $scope
vm.filter = {
itemsPerPage: 4
};
vm.makeRequest = function(numberList) {
console.log("Received submit order");
$http({
method: 'GET',
url: 'https://myNumberServer.com/api/v1/getPrimes',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function successCallback(response) {
numberList = response.data.entries;
vm.totalPages = response.data.totalPages;
vm.filter = {
itemsPerPage: 4
};
console.log("success!");
}, function errorCallback(response) {
console.log('Error: ' + response);
});
};
},

Angular Promise Response Checking

I am doing some http calls in Angular and trying to call a different service function if an error occurs. However, regardless of my original service call function return, the promise it returns is always "undefined". Here is some code to give context:
srvc.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
var promise = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
})
.success(function (data) {
return data;
})
.error(function (error) {
return [];
});
return promise;
};
Then, in the controller:
for (var applicant in $scope.applicants) {
$scope.sendATSError($scope.sendApplicantsToSR($scope.applicants[applicant]), applicant);
}
$scope.sendATSError = function (errorCheck, applicantNumber) {
if (angular.isUndefined(errorCheck)) {
console.log(errorCheck);
AtsintegrationsService.applicantErrorHandling($scope.applicants[applicantNumber].dataset.atsApplicantID);
}
};
However, it is always sending errors because every response is undefined. How can I differentiate between the two returns properly? Thank you!
Looking at angular documentation, the sample code is
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
based on that - your first code snippet should be
srvc.sendApplicantsToSR = function(applicant) {
var applicantURL = {
snip
};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
});
};
As others have said, $http's .success() and .error() are deprecated in favour of .then().
But you don't actually need to chain .then() in .sendApplicantsToSR() as you don't need (ever) to process the successfully delivered data or to handle (at that point) the unsuccessful error.
$scope.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
url: applicantURL,
data: applicant
});
};
Now, in the caller (your line of code in the for loop), a promise is returned (not data) and that promise will, on settling, go down its success path or its error path. Exactly what happens on these paths is determined entirely by the callback functions you write in one or more chained .thens .
So what you need to write is a kind of inside-out version of what's in the question - with $scope.sendApplicantsToSR() on the outside and $scope.sendATSError() on the inside - and linked together with a .then().
for (var prop in $scope.applicants) {
var applicant = $scope.applicants[prop];
$scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
// Above, `null` means do nothing on success, and
// `function(e) {...}` causes the error to be handled appropriately.
// This is the branching you seek!!
And by passing applicant, the error handler, $scope.sendATSError() will simplify to :
$scope.sendATSError = function (applicant) {
return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID); // `return` is potentially important.
};
The only other thing you might want to know is when all the promises have settled but that's best addressed in another question.
You should return your promisse to be handled by the controller itself.
Simplifying:
.factory('myFactory', function() {
return $http.post(...);
})
.controller('ctrl', function(){
myFactory()
.success(function(data){
// this is your data
})
})
Working example:
angular.module('myApp',[])
.factory('myName', function($q, $timeout) {
return function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Foo');
}, 2000);
return deferred.promise;
}
})
.controller('ctrl', function($scope, myName) {
$scope.greeting = 'Waiting info.';
myName().then(function(data) {
$scope.greeting = 'Hello '+data+'!';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
{{greeting}}!
</div>

When try to call function from Controller it doesn't respond

I'm trying to call a function in my jointController from other javascript file.
var app1 = angular.module('jointApp',[]);
var createStateBox = function(label,color){
var state = new uml.State({
position: {x: 0, y: 0},
size: {width: 200, height: 100},
name: "<<"+label+">>",
events: [label+" box"],
attrs:{rect:{fill:color},path:{"stroke-width":0}}
});
app1.controller('jointController', function($scope) {
$scope.setDecision(state);
alert("This is reached");
});
paper.model.addCell(state);
}
Here is the code in jointMod.js which contains jointController
var app = angular.module('jointApp', []);
function JointController($scope, $http, $filter) {
$scope.list = [];
$scope.newMsg = 'hello';
$scope.newDecision;
$scope.setMsg = function(msg) {
$scope.newMsg = msg;
}
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
msg: $scope.newMsg
})
});
$scope.setDecision = function(decision){
$scope.newDecision = decision;
alert("one two one two")
console.log(decision);
}
$http({
method: 'POST',
url: 'http://213.65.171.121:3000/decision',
data: $scope.newMsg,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
str.push(encodeURIComponent("action") + "=" + encodeURIComponent(obj));
return str.join("&");
}
}).success(function(data, status, header, config) {
$scope.list.push(status);
}).error(function(data, status, header, config) {
$scope.list.push(status);
});
};
};
I have the alert and console log in there to make sure if they can be reach but they do not responed.
The code you provided will not function as you may think. Atleast not if you use both together.
Both codes introduce a new module jointApp and actually only the first one defines a controller. The $scope of that controller is NOT the same of the function in your second code.
If you want to call a method from outside of a controller take a look at events in angular. That would be the best way to archive this. You could also use a dummy object and two-way-bind it (scope: { dummy: '=' }) and then call the method you create on that object in your directive from other code-parts.
Take a look at this plnkr demonstrating both approaches.
http://plnkr.co/edit/YdcB10UpXGqKAxYzXISL?p=preview

Angular $http service cache not working properly

I have a $http service in angular js which has a cache enable for it. When first time load the app service gets call and get cache. Now when i call the service anywhere from the same page the data comes from cache but when i change the page route and again call the service from another page the data come from server(i am just changing the route not refreshing the page)
Edit =>
Code was working !! On route the data also came from cache but it took more time as there are few other call as. It just took more time then i accepted the cache to respond .If i call same from any click event then it will take 2ms to 3ms
here is my service
commonServicesModule.service('getDetails', ['$http', 'urlc',
function($http, urlc) {
return {
consumer: {
profile: function(id) {
return $http({
url: urlc.details.consumer.profile,
cache: true,
params: {
'consumer_id': id,
'hello': id,
},
method: 'GET',
}).success(function(result) {
return result;
});
},
}
}
}
])
Call from controller :
start = new Date().getTime();
/*get user information */
getDetails.consumer.profile('1').then(function(results) {
console.log('time taken for request form listCtrl ' + (new Date().getTime() - start) + 'ms');
});
when i call this from anywhere else after route it take the same time.
Try moving the consumer object into the body of the function, and return a reference to it, like so:
commonServicesModule.service('getDetails', ['$http', 'urlc', function($http, urlc) {
var getConsumer = {
profile: function(id) {
return $http({
url: urlc.details.consumer.profile,
cache: true,
params: {
'consumer_id': id,
'hello': id,
},
method: 'GET',
}).success(function(result) {
return result;
});
}
};
return { consumer: getConsumer };
}]);

Categories

Resources