I have a simple page with an input field and a button to change the name. The name changes on ng-click of the button, but what I want to happen is below the hello {{name}} text to have a log of the previous names selected and the time they were selected. eg
Hello Tom
- sam - 1414530148463
- Mick - 1414530159015
I have tried the below in this fiddle http://jsfiddle.net/4ybmyf1a/2/ but get the message, 'cannot read property push of undefined' (I have commented out in myCtrl so that the fiddle would run)
<div ng-controller="MyCtrl">
<input type="text" ng-model="updatedname" />
<input type="button" value="Change name" ng-click="changeName(updatedname)"/>
<br/>
Hello, {{name}}!
<ul>
<li ng-repeat="names in namelog">{{nameLog.value}} - {{nameLog.time}}</li>
</ul>
</div>
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
var userService = {};
userService.name = "John";
userService.ChangeName = function (value) {
userService.name = value;
};
userService.NameLog = function (value) {
userService.nameLog.push ({
"value":value,
"time" :Date.now()
});
};
return userService;
});
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
$scope.updatedname="";
$scope.changeName=function(data){
$scope.updateServiceName(data);
}
$scope.updateServiceName = function(name){
UserService.ChangeName(name);
//UserService.NameLog(name);
$scope.name = UserService.name;
//$scope.nameLog = UserService.NameLog;
}
}
I have looked at also adding in userService.nameLog = [] to stop the undefined issue however this does not push the items like I want it.
userService.NameLog = function (value) {
userService.nameLog = [];
userService.nameLog.push ({
"value":value,
"time" :Date.now()
});
};
How am I able to acheive this?