AngularJS:如何从子指令访问父控制器的作用域项

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

本文关键字:控制器 作用域 访问 指令 AngularJS      更新时间:2023-09-26

我的html视图如下

学校.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>

控制器:学校控制器.js

(function() {
 var app = angular.module("SchoolApp")
 var SchoolController = function ($scope,$rootScope,...)
   {
      $scope.profileId = myData.profileId;
   }

学生档案控制器.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,但它不起作用。我得到的配置文件ID为"未定义"。如何在子指令中获取父控制器的范围项配置文件 ID?

它看起来像我的身体控制器在我的指令加载后分配配置文件 ID。因此,当第一次加载我的指令时,它不会从其父范围获取任何 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