2017-05-03 33 views
0

我有麻煩在訪問父控制器方法/變量在$ 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()

+1

的可能的複製[使用controllerAs語法時傳遞電流範圍modalInstance](http://stackoverflow.com/questions/33164281/pass-current-scope-to-modalinstance-when-using -controlleras-syntax) – estus

+0

是否有任何特定的原因,你不想在$ uibModal中傳遞$ scope? –

回答

1

使用不同的在模態定義對象的controllerAs屬性ENT名:

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


嵌套的範圍是,我們看到從控制系統語法巨大的回報,往往我們不得不使用電流範圍的$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> 

沒有哈克$parent電話。如果控制器在DOM /堆棧中的位置發生變化,順序$parent.$parent.$parent.$parent中的位置可能會改變!從詞彙上訪問示波器非常有意義。

Todd Moto: Digging into Angular’s 「Controller as」 syntax (Nested scopes)