加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs directive内部controller link函数理解

发布时间:2020-12-17 10:13:30 所属栏目:安全 来源:网络整理
导读:directive内部的controller跟mvc中controller不一样,这里的controller是用来给我们的指令暴露public 方法供外部去调用的。 link: 是用来处理指令内部事务的,包括:给元素绑定事件/数据之类的。 require 之后,link就会多一个参数(第四个参数,scope,ele

directive内部的controller跟mvc中controller不一样,这里的controller是用来给我们的指令暴露public 方法供外部去调用的。


link: 是用来处理指令内部事务的,包括:给元素绑定事件/数据之类的。


require 之后,link就会多一个参数(第四个参数,scope,element,attrs,superCon),angularjs就会自动将superCon注射到link函数,这样就可以用superCon 内部控制器(controller)暴露出来的方法。


指令之间的数据交互,通过内部的controller 暴露出来的方法,来给外部进行调用的。


directive代码

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,attrs) {
            element.addClass('btn btn-primary');
            element.bind("mouseenter",function() {
                console.log(scope.abilities);
            });
        }
    }
});
myModule.directive("strength",function() {
    return {
        require: '^superman',supermanCtrl) {
            supermanCtrl.addStrength();
        }
    }
});
myModule.directive("speed",supermanCtrl) {
            supermanCtrl.addSpeed();
        }
    }
});
myModule.directive("light",supermanCtrl) {
            supermanCtrl.addLight();
        }
    }
});


html代码

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

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/bootstrap.css">
    <script src="../library/angular.js"></script>
	<script src="../js/directives/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>
参照 慕课网 angularjs实战

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读