简体   繁体   English

Angular.js:如何在指令中访问控制器作用域?

[英]Angularjs: How to access controller scope in directive?

I have 2 elements like so: 我有两个像这样的元素:

<div ng-hide="showDiv"></div>
<div ng-show="showDiv">
   <div directive></div>
</div>

And a directive like so: 像这样的指令:

app.directive ('directive', [
   ...
   controller: [
        '$scope',
        function ($scope) {
          $scope.accept = function () {
            $scope.showDiv = false;
          };
        }
      ],
   ....
]

I tried to use $scope.showDiv within the directive to toggle the controller but it didn't work. 我试图在指令中使用$ scope.showDiv来切换控制器,但是它不起作用。 How do I access the controller's scope within the directive? 如何在指令中访问控制器的作用域?

console.log($scope) in the directive shows $scope.showDiv === false though $scope.showDiv === true in the controller. 指令中的console.log($ scope)在控制器中显示$ scope.showDiv === false,尽管$ scope.showDiv === true。

You can simply achieve this if you use controllerAs syntax. 如果使用controllerAs语法,则可以简单地实现此目的。

HTML 的HTML

<div ng-hide="showDiv"></div>
<div ng-show="showDiv">
   <div dir-show-div is-shown="showDiv"></div>
</div>

Directive 指示

angular
   .module('app')
   .directive('dirShowDiv', dirShowDiv);

function dirShowDiv() {
   var directive = {};

   directive.scope = {
      isShown: '='
   };
   directive.controller = 'DirController';
   directive.controllerAs = 'vm';

   return directive;
}

Directive Controller 指令控制器

angular
    .module('app')
    .controller('DirController', DirController);

function DirController() {
   var self = this;

   self.accept = accept;

   function accept() {
      self.isShown = false;
   }
}
$scope.showDiv = true

is a primitive value and is not inherited by the directive's scope. 是原始值,并且不被指令的范围继承。 Assigning the value to an object allows the directive's scope to inherit the object, and any changes in the directive scope will be passed back up to the parent scope. 将值分配给对象可以使指令的作用域继承该对象,并且该指令作用域中的任何更改都将传递回父作用域。

//controller
//change primitive to object
$scope.showDiv = {status: true};

//template
//directive names in HTML are usually in kebab case but i'm keeping it obvious for now.
//Pass showDiv object to directive
<div ng-show="showDiv.status">
    <div directive showDiv="showDiv"></div>
</div>

//directive
app.directive ('directive', [
  ...
  return {
    scope : {
       //bind directive scope to parent
       showDiv: '=showDiv'
    }
    controller: [
        '$scope',
        function ($scope) {
          $scope.foo = function () {
            //Changing object in directive will also update parent scope. 
            $scope.showDiv.status = false;
          };
        }
      ],
   ....
]

//controller
//after $scope.foo executed in directive
console.log(showDiv) === {status: false}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM