[英]AngularJS : How do access parent controller's scope item from the child directive?
我的HTML視圖如下
School.html
<html>
<body>
<div class="col-xs-9">
<!-- major bootstrap html code goes over here -->
</div>
<div class="col-xs-3">
<!--Call to directive goes here-->
<div student-profile ngInit="studentId=profileId"></div>
</div>
</body>
</html>
控制器: SchoolController.js
(function() {
var app = angular.module("SchoolApp")
var SchoolController = function ($scope,$rootScope,...)
{
$scope.profileId = myData.profileId;
}
studentprofileController.js
(function() {
var app = angular
.module("SchoolApp")
.directive('studentProfile',studentProfileDirective)
function studentProfileDirective(){
return {
restrict :'AE',
replace:'true',
controller:studentProfileController,
bindtocontroller:true,
template:'student-profile.html'
}
studentProfileController.inject=['$scope','$rootScope',...];
function studentProfileController($scope,$rootScope,....)
{
var ProfileID = $scope.$parent.profileId;
console.log("ProfileID",ProfileID);
}
};
我試過$ scope。$ parent.profileId不能正常工作。 我將ProfileID設為“未定義”。 我如何在子指令中獲取父控制器的范圍項profileId?
看起來像我的身體控制器在我的指令加載后分配了profileId。 因此,當我的指令第一次加載時,它不會從其父范圍獲得任何profileId。 在這種情況下,我該如何稍后進行同步?
將主體控制器移至body
標簽。
<html>
<body ng-app="SchoolApp" ng-controller="SchoolController">
<div class="col-xs-9">
<!-- major bootstrap html code goes over here -->
</div>
<div class="col-xs-3">
<!--Call to directive goes here-->
<div student-profile ngInit="studentId=profileId"></div>
</div>
</body>
</html>
並且一定要聲明它。
(function() {
var app = angular.module("SchoolApp")
//Be sure to declare it
app.controller("SchoolController", SchoolController);
//
var SchoolController = function ($scope,$rootScope,...)
{
$scope.profileId = myData.profileId;
}
通過將ng-controller
指令放在body
層次結構的頂部, $compile
服務將在編譯其他指令之前首先實例化它。
構建自定義指令時,您可以控制它是共享父作用域還是創建子作用域。 默認情況下,它共享父視圖的范圍。 如果在指令對象上設置scope: true
,它將使用從父視圖的范圍原型繼承的子范圍。 如果在指令對象上設置scope: {}
,它將創建一個隔離范圍,該范圍不從父視圖的范圍繼承任何內容。
因此,要根據指令的聲明方式回答您的問題,您可以使用$ scope變量本身訪問父范圍,因為它是共享的。
https://github.com/angular/angular.js/wiki/Understanding-Scopes#directives
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.