Javascript 将表单输入保留在路线更改AngularJS上
考虑这个例子: Main.html:Javascript 将表单输入保留在路线更改AngularJS上,javascript,angularjs,angular-routing,Javascript,Angularjs,Angular Routing,考虑这个例子: Main.html: <html> <body> <script> angular.module('app', ['ngRoute']).config(function($routeProvider) { $routeProvider .when('/page1', { templateUrl : 'page1.html' }
<html>
<body>
<script>
angular.module('app', ['ngRoute']).config(function($routeProvider) {
$routeProvider
.when('/page1', { templateUrl : 'page1.html' })
.when('/page2', { templateUrl : 'page2.html' })
})
</script>
<a href="#page1/">Page 1</a>
<a href="#page2/">Page 2</a>
<div ng-view></div>
</body>
</html>
angular.module('app',['ngRoute']).config(函数($routeProvider){
$routeProvider
.when('/page1',{templateUrl:'page1.html'})
.when('/page2',{templateUrl:'page2.html'})
})
页面1.html
Page 1: <input type="text">
第1页:
页面2.html
Page 2: <input type="text">
第2页:
演示:
单击第1页或第2页的其中一个链接。在字段中输入一些内容,然后单击相反的链接。该字段已清除。有没有办法保持输入?如果用户正在发布评论,但在保存更改之前必须登录,则此功能非常有用。用户将被重定向到登录页面,登录后将被重定向回输入页面 您可以使用
工厂
(或值
)提供在控制器之间共享对象的简单方法
以下是一个例子:
myApp.factory('DataHolder', function (){
return { myData: true, otherData: 'haha' };
});
// Or, with value
myApp.value('DataHolder', { myData: true, otherData: 'haha' });
然后,在控制器中:
myApp.controller('CtrlA', function ($scope, DataHolder){
$scope.sharedData = DataHolder;
});
myApp.controller('CtrlB', function ($scope, DataHolder){
$scope.sharedAsWell = DataHolder;
});
在你的观点中:
<div ng-controller="CtrlA">
The other data is: {{sharedData.otherData}}, and mine is: {{sharedData.myData}}
</div>
<div ng-controller="CtrlB">
<input type="text" ng-model="sharedAsWell.otherData"/>
</div>
另一个数据是:{{sharedData.otherData}},我的数据是:{{sharedData.myData}}
多亏了@ippi,他实现了它:对于类似的东西,我通常默认使用指令,因为您将功能注入HTML元素,而不是服务/工厂。(但这只是个人偏好)。无论如何,这里有一个指令的示例,它依赖于
localStorage
.directive( 'persist', ['$parse' , function( $parse ) {
return {
restrict: 'A',
link: function( $scope, elm, attrs ) {
var set = function( val, type ) {
localStorage.setItem( type, val );
};
var get = function( type ) {
return localStorage.getItem( type );
};
elm.bind( 'change' , function( e ) {
set( this.value, elm.prop('id') );
});
var persistedVal = get( elm.prop('id') );
if ( persistedVal ) {
elm.val(persistedVal)
}
}
}
}]);
我想你可能会对HTML5的存储接口感兴趣:你应该研究angularjs 2Beat me to it,会使用myApp.value('DataHolder',{}),尽管这会让我更容易阅读。这里是根据Ivan的建议更新的op plunk。这对于拯救国家来说似乎有点太麻烦了…:((什么?AngularJS需要这么多tweeking才能保持状态?我对这项技术越来越失望,尽管我在介绍基础知识时很激动。)