【问题标题】:AngularJS data-binding using ui-router and ControllerAs syntax without $scopeAngularJS 数据绑定使用 ui-router 和 ControllerAs 语法,没有 $scope
【发布时间】:2015-02-26 09:32:20
【问题描述】:

我遵循 John Papa 制定的约定,但不幸的是,我并没有真正弄清楚如何使用 ui-router、ControllerAs 和 vm 变量而不是 $scope 将值从子控制器绑定到父控制器。

我做了两个例子,第一个例子说明了工作环境,所以没有 ControllerAs 和正常的 $scope 变量,这是可行的,但是当我将 $scope 更改为

var vm = this; 

它不会处理对子控制器对父控制器所做的任何更改。我真的想让它在不使用某种 PUBSUB 模式的情况下工作,因为这是使用双向数据绑定最重要的特性之一,但我不知道在这种情况下这是否可能?

我创建了两个 Plunker 示例来说明问题:

Plunker 示例 1:

Plunker 示例 2:

第一个示例有效,当更改模板“register-identification.html”中的某些输入字段时,这将直接更改父控制器 (RegisterBaseController) 中的 {{formData}}。

第二个示例不处理任何更改。

我希望我的解释有意义吗?希望有人可以帮助我!

非常感谢!

【问题讨论】:

  • 创建 jsfiddle 或 plunker 来显示您的问题。
  • 添加了 Plunker 示例...

标签: angularjs angularjs-scope angular-ui-router


【解决方案1】:

此方案的行为符合预期,但不是您想要的。

$scope 继承 - 通过引用传递模型

原因是,任何子状态都提供有prototypically inherited 版本的$scope

$childScope = $scope.$new();

这意味着,在父级上创建的任何引用都可以在子级上使用

$scope.Reference = {};
$scope.Reference.A = 1;

$childScope = $scope.$new();
// here both contain 1 as Reference.A

$childScope.Reference.A = 2;

// both contain 2
$childScope.Reference.A === $childScope.Reference.A

用另一个隐藏引用

但你所做的(controllerAs 所做的)是:

$scope.vm = controllerParent;

$childScope = $scope.$new();

$childScope.vm = controllerChild;

vm 本身的引用已更改。

带点的解决方案 - 模型{}

所以,可能的工作是组合:

$scope.Model = {}
$scope.Model.vm = controllerParent;

$childScope = $scope.$new();

$childScope.Model.childVm = controllerChild;
$childScope.Model.vm ... // this is parent controller 

查看文档:

What Do Child States Inherit From Parent States?

主要是:

Scope Inheritance by View Hierarchy Only

请记住,如果您的状态视图是嵌套的,则范围属性只会沿状态链继承。范围属性的继承与您的状态的嵌套无关,而与您的视图(模板)的嵌套有关。

您完全有可能拥有嵌套状态,其模板在您的站点内的各种非嵌套位置填充 ui-views。在这种情况下,您不能期望在子状态的视图中访问父状态视图的范围变量。

检查模型中的

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 2015-02-06
    • 2015-10-22
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2018-09-17
    • 2015-02-26
    相关资源
    最近更新 更多