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

标签 javascript angularjs angularjs-directive angularjs-scope

我的 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/

相关文章:

javascript - 如何在 angularJS 中为一个 View 定义多个 Controller ?

javascript - 如何在 AngularJS 中动态嵌套指令

javascript - 将按钮绑定(bind)到 ng-repeat 内的元素

javascript - Angularjs -> 如何以 Angular 风格初始化变量

angularjs - 指令隔离范围与 attrs.$observe

javascript - $scope、$element 和 $attrs 变量到底如何相关(如果有的话)?

javascript - 无法提交 data-live-search 为 true 的表单(Bootstrap-select)

javascript - 当订阅可观察对象的字段时,订阅不是函数错误

javascript - 使用 jquery 查找下一个最接近的可聚焦元素?

javascript - Angular 2 - 从 promise 中返回 HTTP