我正在实现角度js并且正在尝试获取输入框的值并将其存储到本地存储中。输入由用户输入,它指的是IP地址。
以下是我的HTML代码:
.controller('Ctrl', function($scope) {
$scope.save= function() {
console.log($scope.serverip);
localStorage.setItem('serverip', $scope.serverip);
};
})
以下是我的js代码:
$scope.serverip
为什么通过使用上面的编码,在我将ip地址输入到输入框后,我得到的$("#table-sparkline").find("td").click(function () {
var message = "";
var data = $($(this).parent().children()).map(function () {
message += $(this).text() + ', ';
});
alert(message.substring(0,message.length-2));
});
总是取消定义?
答案 0 :(得分:1)
我找到了正确的答案。我们必须在html中传回serverip
:
<div>
<input ng-model="serverip">
<input type="button" class="button" value="Apply" ng-click="save(serverip)">
</div>
在js文件中:
.controller('Ctrl', function($scope) {
$scope.save = function(serverip) {
console.log(serverip);
localStorage.setItem('serverip', serverip);
};
})
答案 1 :(得分:0)
您是否正确设置了ng-app
和ng-controller
?这是a plunker演示您想要的行为。
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>
控制器:
var app = angular.module('plunker', []);
app.controller('Ctrl', function($scope) {
$scope.save = function() {
$scope.savedip = $scope.serverip
};
})
答案 2 :(得分:0)
这是您正在寻找的完美工作示例:
直播:http://jsbin.com/bifiseyese/1/edit?html,console,output
代码:
<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>