gpt4 book ai didi

javascript - AngularJS : How do access parent controller's scope item from the child directive?

转载 作者:行者123 更新时间:2023-12-03 07:28:24 25 4
gpt4 key购买 nike

我的 html View 如下

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>

Controller :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 为“未定义”。如何在子指令中获取父 Controller 的范围项 profileId?

看起来我的 body Controller 在加载指令后分配了 profileId。因此,当第一次加载我的指令时,它不会从其父作用域获取任何 profileId。在这种情况下我该如何进行稍后的同步?

最佳答案

将主体 Controller 移至 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 服务将在编译之前先实例化它其他指令。

关于javascript - AngularJS : How do access parent controller's scope item from the child directive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35904311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com