javascript - Angular.JS : views sharing same controller, 模型数据在更改 View 时重置

标签 javascript angularjs

我开始使用 Angular.JS。

我有许多共享同一个 Controller 的 View 。每个 View 都是收集存储在 Controller 中的数据的一个步骤:

$routeProvider.when('/', {
  templateUrl: 'partials/text.html',
  controller: 'itemSubmitter'
});

$routeProvider.when('/nextThing', {
  templateUrl: 'partials/nextthing.html',
  controller: 'itemSubmitter'
});

itemSubmitter Controller :

$scope.newitem = {
  text: null
}

这是第一个 View :

<textarea ng-model="newitem.text" placeholder="Enter some text"></textarea>

<p>Your text is:
{{ newitem.text }}</p>

这有效,实时更新“您的文字是:”段落。

然而,当加载下一个 View 时,{{ newitem.text }} 将重置为其默认值。如何使存储在 Controller 实例中的值在 View 中保持不变?

最佳答案

Controller 在改变路线时被释放。这是一个很好的行为,因为您不应该依赖 Controller 在 View 之间传输数据。最好创建一个服务来处理该数据。

请参阅有关如何正确使用 Controller 的 Angular 文档。 http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

引用文档:

Using Controllers Correctly

In general, a controller shouldn't try to do too much. It should contain only the business logic needed for a single view.

The most common way to keep controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in controllers via dependency injection. This is discussed in the Dependency Injection Services sections of this guide.

Do not use controllers for:

  • Any kind of DOM manipulation — Controllers should contain only business logic. DOM manipulation—the presentation logic of an application—is well known for being hard to test. Putting any presentation logic into controllers significantly affects testability of the business logic. Angular offers databinding for automatic DOM manipulation. If you have to perform your own manual DOM manipulation, encapsulate the presentation logic in directives.
  • Input formatting — Use angular form controls instead.
  • Output filtering — Use angular filters instead.
  • To run stateless or stateful code shared across controllers — Use angular services instead.
  • To instantiate or manage the life-cycle of other components (for example, to create service instances).

关于javascript - Angular.JS : views sharing same controller, 模型数据在更改 View 时重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16210822/

相关文章:

javascript - AngularJS - Textarea 在 ng-click 后不想清除

javascript - 与 IE7 相比,IE8 中外部 javascript 文件的加载顺序是否不同?

javascript - 如何更改javascript中的弹出标题?

javascript - 如何在向每个数组添加键值时设置状态

javascript - AngularJS:如何制作一个波动的进度条?

angularjs - 将选项卡 View 重新定位到 nativescript Angular 的底部

javascript - html5 - 页面之间的无缝音频连接

javascript - 无法使用 JavaScript 更改跨度内容

javascript - AngularJS 中的工厂

javascript - 如何在 ui-sref 标记中放置重新加载选项