CLD*_*Dev 8 state angularjs angular-ui angular-ui-router
我是AngularJS和ui-router的新用户,我正在试图调整范围的管理方式.我期望当状态改变变为非活动状态时,活动控制器的范围将被销毁,但是,似乎并非如此.
我已经从UI-Router的网站修改了这个例子来说明情况(参见下面的plunker).每次触发state route1.list/route2.list时,它们都会在$ rootScope上发出一个事件.收到事件后,将在控制台上打印调试语句.
通过在两个状态之间切换几次,观察到先前初始化的所有控制器都响应该事件.所以看来它们创建的范围从未被破坏过.这种行为有望吗?如果是这样,我该怎么办才能让只有主动控制器响应一个事件?
码:
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/route1")
Run Code Online (Sandbox Code Playgroud)
这是route1
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html"
})
.state('route1.list', {
url: "/list",
templateUrl: "route1.list.html",
controller: function($rootScope, $scope){
$rootScope.$emit("eventCT1");
$rootScope.$on("eventCT2", fn);
function fn () {
console.log("Controller 1 receives an event emitted by Controller 2");
}
$scope.items = ["A", "List", "Of", "Items"];
}
})
Run Code Online (Sandbox Code Playgroud)
这是路线2
.state('route2', {
url: "/route2",
templateUrl: "route2.html"
})
.state('route2.list', {
url: "/list",
templateUrl: "route2.list.html",
controller: function($rootScope, $scope){
$rootScope.$emit("eventCT2");
$rootScope.$on("eventCT1", fn);
function fn () {
console.log("Controller 2 receives an event emitted by Controller 1");
}
$scope.things = ["A", "Set", "Of", "Things"];
}
})
...
Run Code Online (Sandbox Code Playgroud)
如果我们想做点什么
1) $rootScope控制器内部(寿命非常有限),
2)当控制器($scope实际上)被销毁时,我们必须销毁它
所以,这是如何挂钩和解钩的方式
// get remove function
var removeMe = $rootScope.$on("eventCT2", ...);
// call that function
$scope.$on("$destroy", removeMe)
Run Code Online (Sandbox Code Playgroud)
但是,在上面的情况下,我们甚至不应该尝试
1)为一个州创建一些控制器动作......
2)并期望它将在不同状态的另一个控制器中调用
这些永远不会生活在一起
| 归档时间: |
|
| 查看次数: |
7512 次 |
| 最近记录: |