Reputation: 2285
I'm implementing angular js and is trying to get the input box's value and store it into the local storage. The input is typed by user and it's refer to ip address.
Below is my html code:
<div>
<input ng-model="serverip">
<input type="button" class="button" value="Apply" ng-click="save()">
</div>
Below is my js code:
.controller('Ctrl', function($scope) {
$scope.save= function() {
console.log($scope.serverip);
localStorage.setItem('serverip', $scope.serverip);
};
})
Why is it by using the above coding, after I key in the ip address into the input box, the $scope.serverip
I get is always undefine?
Upvotes: 6
Views: 6192
Reputation: 2285
I kinda find out the correct answer. We have to pass back the serverip
in the html:
<div>
<input ng-model="serverip">
<input type="button" class="button" value="Apply" ng-click="save(serverip)">
</div>
And in the js file:
.controller('Ctrl', function($scope) {
$scope.save = function(serverip) {
console.log(serverip);
localStorage.setItem('serverip', serverip);
};
})
Upvotes: 1
Reputation: 885
This is the perfect working example of what you are looking:
Live: http://jsbin.com/bifiseyese/1/edit?html,console,output
Code:
<div ng-app="app" ng-controller="Ctrl">
<input type="text" ng-model="serverip"/>
<button ng-click="save()">Save</button>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script type="text/javascript">
angular.module('app',[]).controller('Ctrl', ['$scope', function($scope){
$scope.save = function(){
localStorage.setItem('serverip', $scope.serverip);
console.log("localStorage.serverip = " + localStorage.serverip);
};
}]);
</script>
Upvotes: 0
Reputation: 18833
Have you properly set ng-app
and ng-controller
? Here's a plunker demonstrating the behavior you want.
HTML:
<body ng-controller="Ctrl">
<div>
<input ng-model="serverip">
<input type="button" class="button" value="Apply" ng-click="save()">
</div>
<p>
Saved IP: {{savedip}}
</p>
</body>
Controller:
var app = angular.module('plunker', []);
app.controller('Ctrl', function($scope) {
$scope.save = function() {
$scope.savedip = $scope.serverip
};
})
Upvotes: 0