首页 > 解决方案 > 访问控制器内的指令范围变量

问题描述

parentData 在父控制器中被赋值。

testDir 指令在父 html 中被调用。

<test-dir directive-data="parentData"></test-dir>

testDir 指令:

app.directive('testDir', function () {
  return {
   restrict: 'E',
   scope: {
    directiveData: '='   
   },
   controller: 'myctrl',
   templateUrl: 'view/myView.html'
  };
});

myCtrl 控制器:

app.controller('myCtrl', ['$scope', function($scope) {
   $scope.newVar = $scope.directiveData;
   console.log($scope.directiveData); //printing undefined.
   console.log($scope); //prints the scope objects, directiveData is having the correct value passed from the parent controller
   console.log($scope.new); //undefined
   /* remaining code using the variable newVar */
}]);

我的视图.html

<div>
{{directiveData}} <!-- displaying the proper value -->
</div>

我无法访问控制器内的指令范围。但是,它正在打印在 html 中。

但是在使用超时或监视功能时,范围变量也可以在控制器中访问。

我假设控制器是首先创建的,稍后的指令就会出现。

我不想使用监视或超时功能来解决此问题。有什么建议吗?

提前致谢!

标签: angularjsscopecontrollerdirectivewatch

解决方案


尝试在指令中添加 bindToController 和 controllerAs。


推荐阅读