Angularjs 我可以从控制器调用的角度指令中的函数

Angularjs 我可以从控制器调用的角度指令中的函数,angularjs,Angularjs,是否可以在可从控制器调用的指令内创建函数。它应该是这样的: HTML: 首先,在HTML中将myDir更改为myDir。在您的情况下,您不需要向您的div提供id: <div my-dir>My dir</div> <button ng-click="clickme()">click me</button> 在控制器中,只需将其称为$scope.dirFunction(): 注意:您不应该在控制器内部进行DOM操作:angular.element

是否可以在可从控制器调用的指令内创建函数。它应该是这样的:

HTML:


首先,在HTML中将
myDir
更改为
myDir
。在您的情况下,您不需要向您的div提供
id

<div my-dir>My dir</div>
<button ng-click="clickme()">click me</button>
在控制器中,只需将其称为
$scope.dirFunction()


注意:您不应该在控制器内部进行DOM操作:
angular.element('#myDir').dirFunction()是在angularjs中编写代码的糟糕方式。将此保存到指令中。

只是想用一个解决方案来更新此内容:这是Plunk-

基本上,我使用数组中的scope变量扩展了上述CodeZilla的解决方案

$scope.func = [];
然后将要调用的函数的名称传递到指令属性functionname中

<div mydir name="dir1" functionname="sayhello1">Directive dir1</div>
在指令本身中,我们使用compile在指令内创建将从控制器调用的函数

app.directive('mydir', function () {
    return {
    scope: true,
    compile: function (tElement, tAttrs, transclude) {
        return function postLink(scope, iElement, iAttrs, controller) {
            scope.$parent.func[iAttrs.functionname] = function (){
                alert("update something in " + iAttrs.name);
            }

        }
    }
}
});
或者,您可以使用链接功能-其工作原理相同:

app.directive('mydir', function () {
    return {
        scope: true,
        link: function (scope, element, attrs) {
            scope.$parent.func[attrs.functionname] = function () {
                console.debug("update something in " + attrs.name);
            }
        }
    }
});

就这样

我想调用angular.element('#myDir').dirFunction(),因为我不想同时对所有指令启动函数,如果我调用$scope.dirFunction,就会出现这种情况。有没有一种方法可以选择在哪个指令上调用函数?实际上,考虑一下,我想我可以执行scope[attrs.comboName].dirFunction()=function(){…}-我会试试
$scope.func = [];
<div mydir name="dir1" functionname="sayhello1">Directive dir1</div>
$scope.callDir1 = function (){
    $scope.func['sayhello1']();
}

$scope.callDir2 = function (){
    $scope.func['sayhello2']();
}
app.directive('mydir', function () {
    return {
    scope: true,
    compile: function (tElement, tAttrs, transclude) {
        return function postLink(scope, iElement, iAttrs, controller) {
            scope.$parent.func[iAttrs.functionname] = function (){
                alert("update something in " + iAttrs.name);
            }

        }
    }
}
});
app.directive('mydir', function () {
    return {
        scope: true,
        link: function (scope, element, attrs) {
            scope.$parent.func[attrs.functionname] = function () {
                console.debug("update something in " + attrs.name);
            }
        }
    }
});