angularjs指令系统系列课程(5):控制器controller

时间:2021-05-29 13:37:32

这一节我们来说一下controller这个参数

一.指令控制器的配置方法:

对于指令我有两种配置路由的方式:1.在html中直接引用,2,在指令的controller参数里定义

第一种:在html中直接引用

我定义一个controller:其中newsApp为我自定义的app模块。

js:controller

var newsApp=angular.module('newsApp',{});
newsApp.controller('ForDirective', function() {
alert("this is a directive controller");
});

js:directive

newsApp.directive('helloDirective', function() {
return { }
});

html

<section>
<div hello-directive ng-controller="ForDirective"></div>
</section>

这种方式大家都很熟悉

第二种:在指令的controller参数里定义

可取值:string或者function

该controller可以是已经定义在app上的一个controller,比如:{controller:'ForDirective'}

也可以是匿名函数,及:{controller:function(){}}

该controller是对所有其他指令共享的,自定义的其他指定均可以调用其中的一些方法

还是刚刚的例子,我切换为在指令里设置controller

js:directive

newsApp.directive('helloDirective', function() {
return {
controller:'ForDirective'
}
});

或者:

newsApp.directive('helloDirective', function() {
return {
controller: function() {
alert("this is a directive controller");
}
}
});

html:

<section>
<div hello-directive></div>
</section>

二.指令控制器的常用依赖服务

指令控制器,可以注入任意可以被注入的ng服务。我们介绍一些服务来了解下他们的作用

  1.$scope

    指令当前作用域

  2.$attrs

    指令作用Dom元素的属性集合对象

    这个属性集其实就是把元素的属性和值封装为一个json对象:{id:'obj',name:'myname'}

  3.$element

    指定作用的Dom元素

    可以理解为jquery里面的$('#id')

  4.$transclude

    在使用该嵌入链接函数时,一定要先将transclude参数设置为true,不然$transclude会为undefind

    我们看一个例子:

js:directive

newsApp.directive('helloDirective', function() {
return {
transclude: true,
controller: function($element, $transclude) {
$transclude(function(clone) {
$element.append(clone);
});
}
}
});

html

<section>
<div hello-directive>
这是原先的内容
</div>
</section>

运行效果:

angularjs指令系统系列课程(5):控制器controller查看源码:angularjs指令系统系列课程(5):控制器controller

我们没有在指令模板里加入带 ng-transclude的元素,但是 原先的内容依旧输出,

我们来分析一下:

首先,参数transclude:true,就是告知要嵌入以前的内容,这样 指令作用的dom元素就被clone了一份保留下来,保留在$transclude的回掉函数的参数clone里面,clone这个实体就是被保留的元素。

我们在controller里面又将其添加到页面中,于是实现了那种效果

对$scope,$element,$attrs,$transclude的综合应用能使我们自定义指令做成很方便我们使用的组件