且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在UI路由器改变路径之前,销毁范围

更新时间:2022-11-16 23:04:12

我会说,你体验到什么是有点不同的比你描述的,或你以为发生了什么。请检查该例如:

I would say, that what you experience is a bit different than you described, or you thought what is happening. Please, check for example this:

  • How do I share $scope data between states in angularjs ui-router?
  • scope and controller instantiation with ui router

在一般情况下,一旦状态变化做(不拒绝),在 $范围是肯定的摧毁。如果我们然后再返回,新的 $范围是为我们创造。但是,这的 $范围的创建是这样的:

In general, once the state change is done (not rejected), the old $scope is for sure destroyed. If we navigate then back, new $scope is created for us. But this $scope is created this way:

viewDirective.js

    function updateView(firstTime) {
      var newScope,
          name            = getUiViewName(scope, attrs, $element, $interpolate),
          previousLocals  = name && $state.$current && $state.$current.locals[name];

      if (!firstTime && previousLocals === latestLocals) return; // nothing to do
      // HERE
      newScope = scope.$new();
      ...

的结构: $范围新(); 是理解的关键。这实际上意味着,我们使用原型继承

The construct: scope.$new(); is a key to understanding. This in fact means, that we use prototypical inheritance

  • What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

这简而言之可以描述:

我们提供了一个 $范围已克隆了其母公司的所有属性。

we are provided with a $scope which has cloned all the properties from its parent.

所以,如果父母中含有一定的参考(路径中有'。')这样

So if parent contains some reference (has '.' in the path) like this

// parent scope
$scope.Model = {
  ...
};

和任何一个孩子的状态将改变,像这样

And any child state will change that like this

$scope.Model.name = "User";

这价值将被存储在状态的 $范围的又一次......可用于该州的任何一个孩子

That value will be stored in parent state $scope and available again ... for any next child of this state.

请注意:同一 viewDirective.js但elswhere 可以用来证明一个事实 - $范围破坏 如果我们离开的状态:

NOTE: the same viewDirective.js but elswhere could be used to demonstrate the fact - $scope is destroyed if we leave the state:

    function cleanupLastView() {
      if (previousEl) {
        previousEl.remove();
        previousEl = null;
      }

      if (currentScope) {
        currentScope.$destroy();
        currentScope = null;
      }
      ...

扩展

我创建 rel=\"nofollow\">工作的例子,这两个状态:

I created a working example here, with these two states:

.controller('ParentCtrl', ['$scope', function ($scope) { 
  $scope.Model = {
    SharedName: "This is shared name",
  }
  $scope.NotSharedName = $scope.NotSharedName 
                      || "This name is cloned, but then lives its own way";
}])
.controller('ChildCtrl', ['$scope', function ($scope) {}])

和这两种方式如何改变值的(一切都将遵循上述逻辑)的:

And these two ways how to change values (all will follow the logic described above):

<p>this will be shared among all children and parent
  <input ng-model="Model.SharedName" />
</p>
<p>this will always copied from parent, live then in each child
  <input ng-model="NotSharedName" />
</p>

检查一下这里