指令和自定义方法/html

Directive at angularjs and custom method/html

本文关键字:html 自定义方法 指令      更新时间:2023-09-26

我有这样的代码:

<body ng-controller="testController">
    <div test-directive transform="transform()">
    </div>

    <script type="text/ng-template" id="testDirective.html">
        <div>
            <p>
                {{transform()}}
            </p>
        </div>
    </script>
    <script>
        angular.module("Test", [])
        .directive("testDirective", function() {
            return {
                templateUrl: "testDirective.html",
                scope: {
                    transform: "&"
                },
                link: function(scope) {
                }
            };
        })
        .controller("testController", function($scope) {
            $scope.transform = function() {
                return "<a ng-click='somethingInController()'>Do Something</a>";
            };
            $scope.somethingInController = function() {
                alert("Good!");
            };
        });
    </script>
</body>

所以基本上我想要完成的是创建一个带有一个方法的指令,这个方法将从控制器调用。该方法将对传递的值做一些事情(在本例中它没有接收到任何东西,但在实际代码中它接收到了)。

直到那个点都在工作。然而,我想做的下一件事是创建一个将调用控制器中的方法的元素。指令不知道元素是什么类型(可以是任何类型),也不知道方法是什么类型。有什么办法吗?

小提琴的例子:

http://jsfiddle.net/abrahamsustaita/C57Ft/0/- 0版

http://jsfiddle.net/abrahamsustaita/C57Ft/1/-版本1

小提琴工作示例

http://jsfiddle.net/abrahamsustaita/C57Ft/2/- Version 2

版本2现在正在工作(我不确定这是否是要走的路,但它工作…)。但是,我不能在父控制器中执行该方法。

是。然而,你的代码有一些问题。我先回答你的问题。

<test-directive transform='mycustommethod'></test-directive>
// transform in the directive scope will point to mycustommethod
angular.module('app').directive('testDirective', function() {
    return {
        restrict: 'E',
        scope: {
            transform: '&'
        }
    }
});

问题是打印html将被转义,您将得到<而不是><(等等)。你可以使用ng-bind-html,但是返回的html不会被绑定。你需要在你的link方法中手动注入html(你可以使用jquery),并使用var compiled = $compile(html)(scope)绑定结果。然后调用ele.after(compiled)ele.replace(compiled)将其添加到您的页面>

我终于可以让它工作了。

解合并。首先,我需要添加另一个指令来解析我想要的元素:

.directive("tableAppendElement", function ($compile) {
    return {
        restrict: "E",
        replace: true,
        link: function(scope, element, attrs) {
            var el = angular.element("<span />");
            el.append(attrs.element);
            $compile(el)(scope);
            element.append(el);
        }
    }
})

这将接收将被追加的元素/文本,然后将其注册到作用域。

然而,问题仍然存在。如何访问控制器的作用域?因为我的指令将被许多控制器使用,并且将取决于控制器的模型,所以我只设置scope: false。这样,控制器中的每个方法现在都可以从指令中访问:D

看到小提琴在这里工作。这对我也有帮助,因为现在不需要传递transform方法,所以控制器也可以处理那个。