gpt4 book ai didi

javascript - 尽管被监视,但 Angular ui-router 中的命名 View 未更新

转载 作者:搜寻专家 更新时间:2023-11-01 05:11:31 24 4
gpt4 key购买 nike

我有一个作用域变量 $scope.foo 我正在监视它。它可以通过表单中的文本字段进行更新。

我在使用 Angular ui-router 呈现的页面上有两个命名 View AB。命名 View A 具有文本表单字段,正在通过 ng-model="foo" 监视 Controller 中的更改。当用户更改 foo 的值时,它会更改正在使用的 Controller 中另一个范围变量 $scope.bar 的值,它是一个数组命名 View B 上的 ng-repeat 指令。 $scope.bar 中的更改是使用 Controller 中的 $scope.$watch 方法进行的。

我面临的问题是,当 foo 更改时,我可以在命名 View A 上的 bar 中看到更改但在命名 View B

有人可以帮我解决这个问题吗?

编辑: Here是这个问题的plunker。

最佳答案

有一个plunker ,这应该表明您的方案正在运行。

该解决方案最重要的部分由以下因素驱动:

Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).

It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states.

让我再次表达:scope 继承仅通过view 嵌套

有了它我们可以创建这个状态定义:

$stateProvider
.state('root', {
url: '/root',
templateUrl: 'tpl.root.html',
controller: 'RootCtrl', // this root scope will be parent
})
.state('root.entity', {
url: '/entity',
views:{
'A': {
templateUrl: 'tpl.a.html',
controller: 'ACtrl', // scope is inherited from Root
},
'B': {
templateUrl: 'tpl.b.html',
controller: 'ACtrl', // scope is inherited from Root
}
}
})

所以状态定义支持嵌套 View - 让我们从中受益并将 $scope.bar 集合放入父级。所有涉及的 View 都可以访问同一个集合:

.controller('RootCtrl', function ($scope, $state) {
$scope.bar = ['first', 'second', 'last'];

})
.controller('ACtrl', function ($scope, $state) {
// *) note below
$scope.foo = $scope.bar[0];
$scope.$watch("foo", function(val){$scope.bar[0] = val; });
})
.controller('BCtrl', function ($scope, $state) {

})

*) note: here we do 1) set from bar 2) $watch and 3) set back to bar to follow the question description... but if the array would contain objects, we can work with them directly... without that overhead, but that's another story...

检查 here这是如何工作的,并且 View A 中的任何更改在 B 中也是可见的...因为继承了对数组 bar 的引用> 在父 $scope 中声明。

关于javascript - 尽管被监视,但 Angular ui-router 中的命名 View 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25418403/

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