一个简单的自定义toast,练习下angularjs 模板编译,$scope和controller绑定

$compile API
  • js
  • css
  • html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var dialogModule = angular.module('dialogModule',['']);
dialogModule.factory("dialog",['$timeout','$templateCache','$compile','$rootScope','$controller',
function($timeout,$templateCache,$compile,$rootScope,$controller){
var dialog = {
toast:function(msg,delay){
delay = delay || 1000;
var template = $templateCache.get("toastDialogTemplate");//获取模板
var scope = $rootScope.$new();//创建作用域
scope.message = msg;
//自定义控制器,第一个参数为控制器构造函数,第二个参数为注入对象
var controllerInstance = $controller(function($scope,$element){
console.log("进入自定义控制器");
$scope.message = $scope.message+",123"
}, {
$scope: scope,//注入$scope
$element: template//注入模板,如有需要还可以向控制器构造方法注入其它参数
});
template = $compile(template)(scope);//编译模板
angular.element("body").append(template);//添加模板到DOM
$timeout(function(){
template.remove();
},delay);
}
};
return dialog;
}]);
  • 创建一个toast方法
  • 获取html模板,模板的代码最好放在index.html上,在页面初始化的时候就存在,方便获取
  • 调用$rootScope.$new()创建一个作用域,该方法返回一个对象,可以像操作普通js对象一样给该对象添加成员变量,在模板中可以访问到添加的变量
  • 调用$controller(func,obj)创建控制器,第一个参数为一个方法,第二个参数为一个对象,该对象的成员变量会注入控制器的构造方法中
  • $compile(template)(scope)编译模板,返回一段html代码,将html放入dom中,toast显示。