Mor*_*yae 4 javascript angularjs angularjs-scope angular-ui-router
我用UI-Router路由.当我将路径从状态更改为另一个状态并返回到相同状态时,我看到状态中存在旧的$ scope (具有它的属性).
我想在状态改变之前销毁那个$ scope,所以当我第二次回到状态时,会有一个干净的新范围.我试图在这个事件中访问范围:
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
// fromState.$scope.$destroy();
});
Run Code Online (Sandbox Code Playgroud)
但是没有任何关于$ scope的参考.我可以在角度改变状态之前访问范围UI-Router吗?
我会说,你所经历的与你描述的有点不同,或者你认为发生了什么.请检查例如:
通常,一旦完成状态更改(未拒绝),旧的 $ scope肯定会被销毁.如果我们导航然后返回,$scope则会为我们创建新的.但是这个$ scope是这样创建的:
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();
...
Run Code Online (Sandbox Code Playgroud)
结构:scope.$new();是理解的关键.这实际上意味着我们使用原型继承
简而言之,可以描述:
我们提供了一个
$scope已从其父级克隆所有属性的.
所以如果父类包含一些引用(在路径中有'.'),就像这样
// parent scope
$scope.Model = {
...
};
Run Code Online (Sandbox Code Playgroud)
任何儿童国家都会改变这种状态
$scope.Model.name = "User";
Run Code Online (Sandbox Code Playgroud)
该值将存储在父状态$ scope中,并再次可用...对于此状态的任何下一个子项.
注意:相同的viewDirective.js但elswhere可用于演示事实 - $scope is destroyed如果我们离开状态:
function cleanupLastView() {
if (previousEl) {
previousEl.remove();
previousEl = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
...
Run Code Online (Sandbox Code Playgroud)
延伸
.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) {}])
Run Code Online (Sandbox Code Playgroud)
这两种方式如何改变价值观(都将遵循上述逻辑):
<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>
Run Code Online (Sandbox Code Playgroud)
检查它在这里
| 归档时间: |
|
| 查看次数: |
7218 次 |
| 最近记录: |