gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:13:27 25 4
gpt4 key购买 nike

我开始使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com