angularjs之间如何实现指令和指令之间的交互

我们看看下面的页面的结构:

<!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>

我们给superman这个指令通过controller方法暴露一组public方法用于给外部调用:

var myModule = angular.module("MyModule", []);
//在模块上面定义了一个自定义的指令superman
myModule.directive("superman", function() {
    return {
        scope: {},
        restrict: 'AE',
        controller: function($scope,$element,$attrs,$transclude) {
          //这里的this就是Constructor {},表示当前的控制器函数本身
            $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');
            //为元素添加class类名并且为元素绑定了mouseenter事件,当鼠标进入到指定的元素的时候会打印相应的数组集合
            element.bind("mouseenter", function() {
                console.log(scope.abilities);
            });
        }
    }
});
myModule.directive("strength", function() {
    return {
        require: '^superman',
        //require设置为字符串代表另外一个指令的名字,require会将控制器注入到其值所指定的指令中,并作为当前指令的链接函数的第四个参数
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addStrength();
        }
    }
});
myModule.directive("speed", function() {
    return {
        require: '^superman',
        //其中^表示:指令会在上游的指令链中查找require参数指定的控制器,?表示如果当前指令没有查到指定的控制器就返回null
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addSpeed();
        }
    }
});
myModule.directive("light", function() {
    return {
        require: '^superman',
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addLight();
        }
    }
});

注意:controller中是为了暴露方法给外部调用,而link用于处理指令内部的事务,如绑定事件和数据等

总结:指令与指令之间的交互是通过为指令指定一个controller函数用于暴露给外部的指令进行调用的!

出处:https://blog.csdn.net/liangklfang/article/details/51316180

https://www.imooc.com/video/4279

猜你喜欢

转载自blog.csdn.net/JackLiu16/article/details/82954001