如何从包含控制器的指令中调用$scope方法



我有一个像这样的部分

<my-partial attr1="some text" attr2="some other text">
   <div ng-show="displayBool">
      <div>{{attr1}}</div>
      <div>{{attr2}}</div>
      <button ng-click="changeBool()">Change var</button>
</my-partial>

呈现

   <div>some text</div>
   <div>some other text</div>

在控制器中我设置了$scope.displayBool = true。指令是这样的:

angular.module('grasshopperApp')
    .directive('myPartial', function () {
        return {
            restrict: 'EA',
            scope: {
                displayBool: '=',
                attr1: '@'
                attr2: '@'
            },
            templateUrl: '../my.html'
        };
    });

displayBool在指令中没有出现,div从未显示,但是当我在开发人员面板中检查隐藏元素时,属性值显示正确。为什么会这样?我怎样才能让这个价值体现出来?

你可以指定一个控制器到你的指令,并设置一些属性。

所以你可以这样做:

指令

(function(){
  function directive() {
    return {
        restrict: 'EA',
        scope: {
            attr1: '@',
            attr2: '@'
        },
        templateUrl: 'template.html',
        //Declare controller for our custom directive
        controller: function($scope){
          //Set displayBool property
          $scope.displayBool = true;
        }
    };
  }
angular
  .module('app')
  .directive('myPartial', directive);
})();
模板

<div ng-show="displayBool">
   <div>{{attr1}}</div>
   <div>{{attr2}}</div>
</div>

<my-partial attr1="some text" attr2="some other text"><my-partial>

您可以看到工作活塞

根据评论中的讨论和OP更新的代码,这里有一个潜在的解决方案。使用双向绑定将displayBool引入指令的隔离范围。我们还使用&修饰符引用控制器的$scope方法changeBool

指令

angular.module('grasshopperApp')
    .directive('myPartial', function () {
        return {
            restrict: 'EA',
            scope: {
                attr1: '@',
                attr2: '@',
                changeBool: '&',
                displayBool: '='
            },
            templateUrl: '../my.html'
        };
    });
模板

 <div ng-show="displayBool">
     <div>{{attr1}}</div>
     <div>{{attr2}}</div>
     <button ng-click="changeBool()">Change var</button>
 </div>

displayBoolchangeBool()都指向指令的隔离作用域。

假设控制器MyController存在,类似于:

angular.module('grasshopperApp')
    .controller('MyController', ['$scope', function($scope) {
        $scope.displayBool = true;
        $scope.changeBool = function() {
            $scope.displayBool = !$scope.displayBool;  
        }  
     }]);

你可以这样使用这个指令:

<div ng-controller="MyController">
    <my-partial 
        attr1="some text"
        attr2="some other text" 
        display-bool=displayBool
        change-bool="changeBool()">
    </my-partial>
</div>

这里display-bool绑定到MyController's $scope变量displayBool, change-bool绑定到MyController's $scope函数changeBool,称为字符串。

我主要是从Angular开发指南中关于指令的那一节开始的:

接下来,我们要在这个对话框中添加按钮,并允许使用该指令的人将自己的行为绑定到该对话框中。

指令中的displayBool是一个属性,它不会从你的html片段的父作用域继承。你的指令必须使用displayBool来决定是否将内容转换到你的指令中。

<my-partial attr1="some text" attr2="some other text" displayBool="true"></my-partial>

最新更新