As a beginner in the world of Angular, I am encountering a strange issue that has me puzzled. My controller has two scope properties - "sentences" and "countVal" which are displayed on my HTML page.
I use a factory called "ModelState" to hold my data, which is populated by the service "UpdatingService."
The problem arises when I try to push data into ModelState.values using "ModelState.values.push(data);" The array length increases to one, but the count value remains unchanged. Additionally, the $watch function in TestCtrl does not log anything to the console. I know there must be something wrong with what I'm doing, but I can't seem to pinpoint it. Here is my HTML code (with the script inline). Thank you in advance for any help.
<!doctype>
<html ng-app="testApp">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.js"></script>
</head>
<body ng-controller="TestCtrl">
<p>Array length : {{ sentences.length }}</p>
<p>Count value : {{ countVal }}</p>
<br>
</body>
<script>
var testApp = angular.module('testApp', []);
testApp.controller('TestCtrl', function($scope, ModelState, UpdatingService) {
$scope.sentences = ModelState.values;
$scope.countVal = ModelState.countVal;
$scope.$watch("countVal", function(newValue, oldValue){
console.log(newValue," ",oldValue);
}, true);
});
testApp.factory('ModelState', function(){
return {
values : [],
countVal : 0
};
});
testApp.service("UpdatingService", function($http, $timeout, ModelState, $q){
var service = {
getData:function(){
var promise = $http.get("http://baconipsum.com/api/?type=meat-and-filler");
promise.success(function(data){
ModelState.values.push(data);
ModelState.countVal++;
});
return promise;
}
};
service.getData();
return service;
});
</script>
</html>