AngularJS指令之间如何交互

半兽人 发表于: 2018-10-02   最后更新时间: 2022-12-10 00:11:20  
{{totalSubscript}} 订阅, 3,229 游览

我们先看一段代码:

html:

<!doctype html>
<html ng-app="MyModule">

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
    <script src="framework/angular-1.3.0.14/angular.js"><//script>
    <script src="Directive&Directive.js"><//script>
</head>

<body>
    <div class="row">
        <div class="col-md-3">
            <superman strength>动感超人---力量</superman>
        </div>
    </div>
    <div class="row">
        <div class="col-md-3">
            <superman strength speed>动感超人2---力量+敏捷</superman>
        </div>
    </div>
    <div class="row">
        <div class="col-md-3">
            <superman strength speed light>动感超人3---力量+敏捷+发光</superman>
        </div>
    </div>
</body>

</html>

注意:元素中调用了多个指令。

js:

var myModule = angular.module("MyModule", []);
myModule.directive("superman", function() {
    return {
        scope: {},
        restrict: 'AE',
        controller: function($scope) {
            $scope.abilities = [];
            this.addStrength = function() {
                $scope.abilities.push("strength");
            };
            this.addSpeed = function() {
                $scope.abilities.push("speed");
            };
            this.addLight = function() {
                $scope.abilities.push("light");
            };
        },
        link: function(scope, element, attrs) {
            element.addClass('btn btn-primary');
            element.bind("mouseenter", function() {
                console.log(scope.abilities);
            });
        }
    }
});
myModule.directive("strength", function() {
    return {
        require: '^superman',
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addStrength();
        }
    }
});
myModule.directive("speed", function() {
    return {
        require: '^superman',
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addSpeed();
        }
    }
});
myModule.directive("light", function() {
    return {
        require: '^superman',
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addLight();
        }
    }
});
  • scope:{}: -- 表示独立的作用域。

  • require: '^superman' -- 此选项是表示依赖哪个指令,link函数中就可以写第4个函数supermanCtrl,AngularJS就会把superman指令注入到supermanCtrl

总结

很多人都有一个疑问,什么时候我该把一些逻辑写在controller里面,什么时候写在link里面,

  • 如果你想让你的指令,暴露一些方法给外部调用,那么就使用controller。
  • link用来处理指令内部的一些事物的,比如给元素绑定事件,绑定数据之类的。
更新于 2022-12-10
在线,5小时前登录

查看AngularJS更多相关的文章或提一个关于AngularJS的问题,也可以与我们一起分享文章