【问题标题】:accessing directive scope variable inside the controller [duplicate]访问控制器内的指令范围变量[重复]
【发布时间】:2018-05-08 15:31:29
【问题描述】:

parentData 在父控制器中被赋值。

正在父 html 中调用 testDir 指令。

<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 */
}]);

myView.html

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

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

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

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

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

提前致谢!

【问题讨论】:

标签: angularjs scope controller directive watch


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2016-03-28
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多