Angularjs:双向数据绑定和控制重载 [英] Angularjs: two way data bindings and controller reload

查看:140
本文介绍了Angularjs:双向数据绑定和控制重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用路由和控制器,那么模型不保存控制器之间重装了状态。在每个航线负载角创建控制器实例和新范围。

If use routing and controllers, then model not save his states between controller reload. Angular create controller instance and new scope on every route load.

例如,I型​​在输入的东西,都NG-模式=东西,转到另一条路线,再回到第一条路线。我所有键入的文本丢失。

For example, i type something in input that have ng-model="something", go to another route, then back to first route. All my typed text is lost.

我需要简单的双向数据改变航线之间的结合。尽可能的简单,就像在knockoutjs ko.observable。或隐像在一个控制器内的角度。也许与控制器单身$范围?

I need simple two way data binding between routes changing. As simple as possible, like ko.observable in knockoutjs. Or implicitly like in angular within one controller. Maybe with singleton $scope for controller?

我找到了路,当我保存路径变迁之间的数据创建服务,并注入到控制器。在控制器的构造函数我创建的模型与服务价值,和$ scope.watch这种模式更改,并在更改I设置模型的服务价值。

I found the way, when i create service for saving data between route changing, and inject it into controller. In controller's constructor i create model with value from service, and $scope.watch this model for changes, and on change i set model's value to service.

有没有更简单的方法?

推荐答案

您是对的 - 服务是这样做的正确的方式。您可以使用它像这样:

You are right - services is right way for doing this. You can use it like so:

app.js

app.factory('paginationService', function() {
    return {
        cur: 1,
        total: 9,
        pageSize: 8
    };
});


app.controller('Page1Ctrl', function($scope, paginationService) {
  $scope.pagination = paginationService;
});

Page1.html

<div ng-controller="Page1Ctrl">
  <h2>Page1</h2>

  <p>curPage: <input type="number" ng-model="pagination.cur" /></p>  
</div>

请参阅完整的例子

这篇关于Angularjs:双向数据绑定和控制重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆