我正在尝试在名为name的字符串上实现文本格式。一旦将字符串输入到html表单中,单击保存按钮后,新字符串格式应呈现在表单下方。 字符串应根据字符串长度更改为大写或小写。 如果字符串长度是偶数,则字符串应更改为大写,如果字符串长度为奇数,则字符串应更改为小写。
我已将用于更改文本案例的逻辑放在' formatFactory' factory。格式方法里面的格式方法'负责更改文本案例。
formattingFactory.js
app.factory('formatFactory', function(){
var formattingFactoryObject = {};
formattingFactoryObject.format = function(name) {
if(name.length % 2 == 0) {
name.toUpperCase();
}else{
name.toLowerCase();
}
}
});
我有以下服务负责保存会话数据,即名称和昵称字符串
sessionService.js
angular.module('app').service('sessionService',[
'$window',
//the $window object provides angular access to the browser's window object
sessionService
]);
function sessionService($window) {
this.save = save;
this.get = get;
this.clear = clear;
function save(key, value) {
$window.sessionStorage.setItem(key, value);
}
function get(key, value) {
return $window.sessionStorage.getItem(key);
}
以下是我的控制器。我在vm.setServiceSession方法中保存会话数据的方法之前调用了更改字符串大小写的方法
sessionController.js
angular.module('app').controller('sessionController',[
'sessionService','formatFactory',
function sessionController(sessionService) {
var vm = this;
vm.getServiceSession = function() {
vm.model = {
name: sessionService.get('name'),
nickname: sessionService.get('nickname'),
status: 'Retrieved by service on ' + new Date()
};
}
vm.setServiceSession = function() {
formattingFactoryObject.format(name);
sessionService.save('name', vm.model.name);
sessionService.save('nickname', vm.model.nickname);
vm.getServiceSession();
}
的index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Services and Factories</title>
<link rel="stylesheet" href="./css/bootstrap.min.css">
</head>
<body ng-controller="sessionController as vm">
<div class="container">
<h1>Services and Factories</h1>
<div class ="form-group row">
<div class ="col-sm-4">
<label>Name</label>
</div>
<div class ="col-sm-8">
<input type = "text" class ="form-control" ng-model ="vm.model.name">
</div>
</div>
<div class ="form-group row">
<div class ="col-sm-4">
<label>Nickname</label>
</div>
<div class ="col-sm-8">
<input type = "text" class ="form-control" ng-model ="vm.model.nickname">
</div>
</div>
<div class = "form-group row">
<div class = "col-sm-8 col-sm-offset-4">
<input type = "button" ng-click = "vm.setServiceSession()" class = "btn btn-primary" value = "Save"/>
<input type = "button" ng-click ="vm.getServiceSession()" class = "btn btn-default" value = "Retrieve from Service"/>
</div>
</div>
<pre>{{vm.model | json }}</pre>
</div>
上面代码的问题是它没有改变字符串的情况,我无法弄清楚原因。
答案 0 :(得分:0)
您需要将name.toLowerCase()
和name.toUpperCase()
的新值分配给新值name
,如@Rajesh在评论中所述,当然还要返回name
在你的工厂结束。您还必须格式化$scope.model.name
,同时将其保存在localStorage中,如下所示:
sessionService.save('name', formatFactory.formattingFactoryObject($scope.model.name));
您还需要重构您的工厂。
我创建了一个有效的Fiddle。