如何从Element指令中公开行为?

时间:2015-04-14 22:24:06

标签: angularjs angularjs-directive

我在调整How to expose behavior from a directive with isolated scope?的解决方案时遇到了问题。我想将我的指令暴露为元素而不是属性:

这是一个JSFiddle。当您单击使用属性方法的第一个按钮时,一切正常。但是第二个按钮使用了Element方法,它给出了一个错误。

以下是代码:

HTML:

<div ng-app="main">
    <div ng-controller="MyCtrl">Click the first button and everything is ok:
        <br>
        <button ng-click="callFnInAttribute()">Call Function in Attribute Directive</button>
        <br>{{errorViaAttribute}}
        <div my-attribute my-fn-via-attribute="fnInCtrlViaAttribute"></div>
        <br>
        <br>But click the second button and you get an error:
        <br>
        <button ng-click="callFnInElement()">Call Function in Element Directive</button>
        <br>{{errorViaElement}}
        <my-element my-fn-via-element="fnInCtrlViaElement"></my-element>
        <br>
        <br>The only difference is the type of directive used. Why does it work with an Attribute type of directive but not with an Element directive?</div>
</div>

JavaScript的:

angular.module("main", []).controller("MyCtrl", function ($scope) {
    $scope.callFnInAttribute = function () {
        try {
            $scope.fnInCtrlViaAttribute();
            $scope.errorViaAttribute = "OK";
        } catch (anError) {
            $scope.errorViaAttribute = "Error: " + anError;
        }
    };

    $scope.callFnInElement = function () {
        try {
            $scope.fnInCtrlViaElement();
            $scope.errorViaElement = "OK";
        } catch (anError) {
            $scope.errorViaElement = "Error: " + anError;
        }
    };
}).directive("myAttribute", function () {
    return {
        require: 'A',
        scope: {
            myFnViaAttribute: '='
        },
        controllerAs: 'chartCtrl',
        bindToController: true,
        controller: function ($scope) {
            $scope.myFnViaAttribute = function () {
                console.log("myFnViaAttribute called");
            }
        }
    };
}).directive("myElement", function () {
    return {
        require: 'E',
        scope: {
            myFnViaElement: '='
        },
        controllerAs: 'chartCtrl',
        bindToController: true,
        controller: function ($scope) {
            $scope.myFnViaElement = function () {
                console.log("myFnViaElement called");
            }
        }
    };
});

这是使用以下AngularJS版本:https://code.angularjs.org/1.1.0/angular.min.js

如何正确地公开Element的行为?

1 个答案:

答案 0 :(得分:1)

我认为您的错误只是来自您在指令中编写require而不是restrict这一事实。 require是为了确保同一元素中存在另一个指令,restrict用于定义指令的HTML结构。

.directive("myAttribute", function () {
  return {
    restrict: 'A', // <-- and not "require"
    scope: {
      myFnViaAttribute: '='
    },
    controllerAs: 'chartCtrl',
    bindToController: true,
    controller: function ($scope) {
      $scope.myFnViaAttribute = function () {
        console.log("myFnViaAttribute called");
      }
    }
  };
})