【问题标题】:Access parent controller in $uibmodal without using scope在 $uibmodal 中访问父控制器而不使用范围
【发布时间】:2017-10-01 12:33:46
【问题描述】:

我无法访问 $uibmodal 中的父控制器方法/变量

我的 HTML 模式:

<div ng-controller="TestCtrl as vm">
  <div class="modal-demo lg">
    <div class="modal-header">
      <h3 class="modal-title" id="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body" id="modal-body">

      qweqweqweqweqw

      {{vm.test}}fwewewerwqqwer
    </div>
    <div class="modal-footer">
      <button class="btn btn-primary" type="button" ng-click="vm.ok()">OK</button>
      <button class="btn btn-warning" type="button" ng-click="vm.ok()">Cancel</button>
    </div>
  </div>
</div>

我的控制器:

AltoDevApp.controller('TestCtrl', ['$uibModal',
    function TestCtrl($uibModal) {
    $uibModal.open({
              ariaLabelledBy: 'modal-title',
              ariaDescribedBy: 'modal-body',
              templateUrl: 'member/professional/profile/education/partials/upload.html',
              controller: angular.noop,
              controllerAs: 'vm'
            });

 vm.ok = function () {
    alert('hi');
  };
    }]);
})();

但是无法从模型中访问 vm.ok()

【问题讨论】:

标签: angularjs angular-ui-bootstrap


【解决方案1】:

在模态定义对象中为controllerAs 属性使用不同的名称:

AltoDevApp.controller('TestCtrl', ['$uibModal',
  function TestCtrl($uibModal) {

    $uibModal.open({
          ariaLabelledBy: 'modal-title',
          ariaDescribedBy: 'modal-body',
          templateUrl: 'member/professional/profile/education/partials/upload.html',
          controller: angular.noop,
          //controllerAs: 'vm'
          //USE different name
          controllerAs: 'modalvm'
     });

     var vm = this;    
     vm.ok = function () {
        alert('hi');
     };
}]);

当子控制器与父控制器绑定到相同的属性名称时,子属性名称 (vm) 会隐藏父属性名称 (vm)。如果孩子绑定了不同的名字,则可以通过原型继承访问父属性。

如需更多信息,请参阅AngularJS Wiki - What are the nuances of scope prototypal inheritance


嵌套作用域是我们从 Controller 中看到作为语法的巨大回报的地方,通常我们不得不使用当前作用域的 $parent 属性来扩展作用域以到达我们需要的地方。

事情更加清晰,变量可以跨范围正确访问:

<div ng-controller="MainCtrl as main">
  {{ main.title }}
  <div ng-controller="AnotherCtrl as another">
    Scope title: {{ another.title }}
    Parent title: {{ main.title }}
    <div ng-controller="YetAnotherCtrl as yet">
      Scope title: {{ yet.title }}
      Parent title: {{ another.title }}
      Parent parent title: {{ main.title }}
    </div>
  </div>
</div>

没有 hacky $parent 电话。如果控制器在 DOM/堆栈中的位置发生变化,则顺序 $parent.$parent.$parent.$parent 中的位置可能会发生变化!词法访问范围非常有意义。

Todd Moto: Digging into Angular’s “Controller as” syntax (Nested scopes)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-22
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2017-01-28
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多