I have a variable called appList that is stored in a service and initialized as [1, 2, 3]. In my controller, I import appList and bind it to the view in a list. There is a function called modifyAppList in the controller that invokes a similar function in the service when a button in the view is clicked. Surprisingly, although the value in the service changes (as confirmed by console logs), the view does not update accordingly. If someone could review the code and provide an explanation for this behavior, I would greatly appreciate it.
NOTE: Changing the contents of modifyAppList() to
appList[0] = 5; appList[1]= 6; appList[2]=7;
will produce the expected result. However, there seems to be some issue with assigning appList to a new array within modifyAppList().
angular.module('app', []);
angular.module('app')
.factory('appService', appService)
function appService(){
var appList = [1,2,3];
var modifyList = [5,6,7];
var modifyAppList = function(){
console.log("At the beginning of modifyAppList: ", appList)
appList = [];
console.log("After appList=[] : ", appList)
for(var i = 0; i < 3; i++){
appList.push(modifyList[i]);
}
console.log("After modification: ", appList)
}
return {
getAppList : function(){
return appList;
},
modifyAppList : modifyAppList
}
}
angular
.module('app')
.controller('appCtrl', appCtrl)
appCtrl.$inject = ['appService'];
function appCtrl(appService){
this.appList = appService.getAppList();
this.modifyAppList = function(){
appService.modifyAppList();
var testList = appService.getAppList();
console.log("After modification, and calling getList() : ", testList)
}
}
<body ng-controller="appCtrl as vm">
<ul>
<li ng-repeat="num in vm.appList" ng-bind="num"></li>
</ul><br>
<button ng-click="vm.modifyAppList()">modifyAppList()</button>
<script src="controller.js"></script>
<script src="service.js"></script>
</body>