5

所以,我可以从子控制器更改模型值,但是当子控制器在时,ng-switch它就不起作用,为什么?我创建了一个示例来演示它。

避免这种情况的一种方法是.在模型名称中使用 ,例如bunnies.kills. 这是一个错误还是一个功能?

使用 Angular 1.0.6

4

4 回答 4

6

使用您的代码结构,在您的子控制器中,您需要更改:

$scope.$parent.kills++;

$scope.$parent.$parent.kills++;

解释MainCtrl的作用域是 的父作用域,但是andSimpleParentCtrl的祖父母。正如其他一些人指出的那样,创建自己的范围,然后您和每个人都创建了.Step1CtrlStep2Ctrlng-switchStep1CtrlStep2Ctrlng-switch

注意:每次单击 1 或 2 按钮时,ng-switch当前匹配的子控制器都将获得一个新范围。

另外:如果您碰巧正在查看 Angular 源代码并想知道ng-switch指令如何在没有属性的情况下创建自己的范围scope,答案是它在其链接方法中手动执行此操作 via scope.$new()。指令ng-includeng-switchng-repeatng-view都以这种方式创建新范围,无论是在链接方法中还是在编译方法返回的链接函数中。

资源:

https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m

于 2013-05-22T20:18:43.673 回答
3

ng-switch 创建自己的子范围,这就是为什么@sh0ber 的答案是让它工作的一种方法。一般来说,模型应该在控制器范围(因此是引用对象)中引用,而不是不是原语。所以使用 a.是一种“最佳实践”。

这不是错误,但也不是功能。这是JavaScript 原型继承与原语一起工作的方式。

于 2013-05-22T20:21:54.353 回答
2

我会对这个问题采取稍微不同的方法。

$scope.$parent我建议您将所有的兔子杀戮逻辑移到共享服务/模型中,而不是使用。

另外,我会尽量避免引用父视图/控制器。引用父级可能会使重用代码变得困难,并且随着项目的增长,调试起来会很痛苦。父母可以知道自己的孩子,但孩子应该对自己的父母知之甚少。

这是更新的 Plunk:http ://plnkr.co/edit/PLDbfU8Fu7m59A42qdR6?p=preview

HTML

<body ng-controller="MainCtrl">
    <p>
        Dead bunnies: <strong>{{Elmer.deadWabbits}}</strong>
    </p>
    <div ng-controller="SimpleParentCtrl">
        <button ng-click="Elmer.killTheWabbit()">Kill from simple parent gun</button>
    </div>
    <hr>
    <div ng-switch="" on="step">
        <div ng-switch-when="first" ng-controller="Step1Ctrl">
            <button ng-click="Elmer.killTheWabbit()">Kill from 1 tab gun</button>
        </div>
        <div ng-switch-when="second">
            <div ng-controller="Step2Ctrl">
                <button ng-click="Elmer.killTheWabbit()">Kill from 2 tab gun</button>
            </div>
        </div>
    </div>
    <hr>
    <p>
        <button ng-click="changeStep('first')">1</button> <button ng-click="changeStep('second')">2</button>
    </p>
</body>

JS

angular.module('plunker', []).
service("Elmer", [function() {
    this.deadWabbits = 0;
    this.killTheWabbit = function() {
        this.deadWabbits++;
    };
}]).
controller('MainCtrl', function($scope, Elmer) {
  $scope.Elmer = Elmer;
  $scope.step = 'first';
  $scope.changeStep = function(name){
    $scope.step = name;
  };
}).
controller('SimpleParentCtrl', function() {}).
controller('Step1Ctrl', function() {}).
controller('Step2Ctrl', function() {});
于 2013-06-28T04:22:11.383 回答
1

避免这种情况的一种方法是使用 . 在模型名称中,例如 bunnies.kills。这是一个错误还是一个功能?

这已经解释了很多次:https ://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance 和 mhevery 的视频

于 2013-05-22T20:33:47.830 回答