AngularJS如何从Directive访问Controller范围

时间:2018-03-21 03:21:50

标签: angularjs angular-directive angular-controller

我正在尝试从指令函数访问父控制器作用域。当我尝试获取$scope.$parent的值时,它会返回对象。但是当我尝试从该对象访问任何变量时,它返回 Undefined

app.controller('myCtrl', function ($scope, $http, $timeout) {

    $scope.init = function(){

        $http.get('url.php').success(function(data){
            $scope.assignmentInfo = data.record;
        });

    };
});


app.directive('getInfo', [function(){
    return {
        restrict: 'A',
        scope:{
            data:'=',
            title: '='
        },
        link:function(scope, elem, attrs){
            scope.$watch('data.visible', function(val){
                // do something

            });
        },
        controller: function($scope) {
            console.log($scope.$parent); // return an object

            console.log($scope.$parent.assignmentInfo); // return undefined


        },
        templateUrl: 'template.html'
    };
}]);

首先console.log($scope.$parent)返回以下输出: enter image description here

$scope.$parent.assignmentInfo返回underfined

如何访问assignmentInfo

1 个答案:

答案 0 :(得分:2)

事实上,这是因为您尝试打印assignmentInfo时尚未分配,所以您应该$watch为它:

angular.module('app', [])
.controller('ctrl', ['$scope', '$timeout', function($scope, $timeout) {
    $timeout(function() {
      $scope.assignmentInfo = 'some data';
    }, 1000)
}])
 .directive('myDirective', function() {
    return {
      scope: {},
      template: '<div>from directive: {{assignmentInfo}}</div>',
      controller: function($scope) {      
        $scope.$watch(function() {
          return $scope.$parent.assignmentInfo;
        }, function(value) {
          if (value){
            console.log(value);
            $scope.assignmentInfo = value;
          }
        })
      }
    }
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>    
  <my-directive></my-directive>
</div>