【问题标题】:$parent not working in ng-include angular [duplicate]$parent 在 ng-include Angular 中不起作用 [重复]
【发布时间】:2018-01-20 18:56:49
【问题描述】:

我正在使用 $scope.$parent 更改子控制器内的变量值,但更改并未反映到其父级。

<div data-ng-if="!addBillDetails">
    <button class="btn btn-small" data-ng-if="trItem.skuId==217"
            data-ng-click="addDetails()">Add Details</button>
</div>
<div data-ng-if="addBillDetails" data-ng-include="'views/test.html'"></div>
$scope.addDetails=function(){
                $scope.addBillDetails=true;
};

test.html 和 testCrl

<div data-ng-controller="testCtrl">
<button type="button" class="btn red" data-ng-click="cancel()">Cancel</button>
    </form>
</div>
$scope.cancel=function(){
   alert("cancel");
  $scope.$parent.addBillDetails=false;
};

【问题讨论】:

  • 不带 $parent 试试!
  • ng-include 创建子作用域。
  • $parent 可以访问父范围权限???
  • 是的,但是由于ng-include 子范围,现在层次结构中有另一个父级。所以它会是$parent.$parent,这很丑。使用如下建议的对象
  • @charlietfl 我觉得controllerAs 是更好的选择,在幕后它使用隐式dot rule:p

标签: javascript html angularjs angularjs-ng-include


【解决方案1】:

这是因为ng-include/ng-if 创建了一个原型继承的子作用域。

让我们从为什么$parent 技巧对你不起作用,基本上addBillDetails 变量没有在$parenttestCtrl 范围内立即分配。由于views/test.html 模板是基于ng-ifng-include 指令组合呈现的。它创建了不同的范围层次结构,请参见下图。

//ng-controller="parentCtrl" `$scope.addBillDetails`
|
|
ng-if
   |
   |- ng-inlcude
      |
      |- ng-controller="testCtrl" ($scope.$parent.$parent.$parent.addBillDetails)

通过查看上图,如果要修改父testCtrladdBillDetails,则必须使用$scope.$parent.$parent.$parent.addBillDetails 才能获得正确的值。检查demo here切勿在您的代码中使用$parent,这会使您的代码紧密结合 html 设计和假设。


在这种情况下,首选使用对象(引用类型变量)或在使用控制器时使用controllerAs 模式(controllerAs version)。

推荐阅读"What are the nuances of scope prototypal / prototypical inheritance in AngularJS?"

HTML

{{model.addBillDetails}}
  <div data-ng-if="!model.addBillDetails">
    <button class="btn btn-small" data-ng-if="trItem.skuId==217" data-ng-click="addDetails()">Add Details</button>
  </div>
  <div data-ng-if="model.addBillDetails" data-ng-include="'views/test.html'"></div>

代码

.controller('parentCtrl', function($scope) {
    $scope.model = {};
    $scope.model.addBillDetails = true;
    $scope.addDetails = function() {
      $scope.model.addBillDetails = true;
    };
})
.controller('testCtrl', function($scope) {
    $scope.cancel = function() {
      alert("cancel");
      $scope.model.addBillDetails = false;
    };
})

Preview

【讨论】:

  • $scope.addBillDetails = true; 需要模型对象更新
  • @charlietfl 感谢提醒队友,我更新了答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 2015-04-21
  • 2014-11-30
  • 2017-02-07
  • 2015-02-20
  • 2014-12-07
相关资源
最近更新 更多