-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangular-directive-demo2.html
More file actions
85 lines (84 loc) · 3.77 KB
/
angular-directive-demo2.html
File metadata and controls
85 lines (84 loc) · 3.77 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>angular-directive-ngModel</title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="app">
<div>
<div ng-controller="DemoController">
<h3>Demo</h3>
<student-card ng-model="guy" on-save="saveEditing()"></student-card>
</div>
</div>
<script type="text/html" id="t1">
<div class="panel">
<h3>student card</h3>
<p>
<span>name:</span>
<input type="text" ng-model="ngModel.$modelValue.name" ng-change="nameChange()">
</p>
<p>
<span>sexy:</span>
<select ng-model="ngModel.$moduleValue.sexy" ng-change="sexyChange()">
<option value="male">male</option>
<option value="female">female</option>
</select>
</p>
<button type="button" name="button" ng-click="onSave()">Save</button>
</div>
</script>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('DemoController', ['$scope', function($scope){
$scope.guy = {
name: 'Lucas',
sexy: 'male'
};
$scope.saveEditing = function(){
// $http.post('...')
console.log($scope.guy.name + ' is saving');
console.log($scope.guy);
};
$scope.nameChange = function(){
console.log('name changing');
};
$scope.sexyChange = function(){
console.log('sexy changing');
}
}]);
app.directive('studentCard', ['$parse', function($parse){
return {
restrict: 'E',
require: ['studentCard', 'ngModel'],
scope: {},
template: function(){
return document.getElementById('t1').innerHTML
},
link: function(scope, element, attr, ctrls){
//link阶段,通过require获取指令自身的控制器,及ngModel指令的控制器
var studentCtrl = ctrls[0];
var ngModelCtrl = ctrls[1];
//并将ngModel指令的控制器,通过自身控制器的init()方法传入到其中
studentCtrl.init(ngModelCtrl);
},
controller: function($scope, $element, $attrs, $transclude){
//创建controller的对外初始化方法,并将外部ngModel的控制器设置本地作用域对象
this.init = function(ngModelCtrl){
$scope.ngModel = ngModelCtrl;
};
//获得on-save属性指向的表达式{{saveEditing()}}
// saveInvoker解析以后回来的函数
var saveInvoker = $parse($attrs.onSave);
$scope.onSave = function(){
//在父域中,执行表达式{{saveEditing()}}——执行父域saveEditing()
// $scope.$parent解析表达的上下文环境
saveInvoker($scope.$parent, null);
}
}
}
}]);
</script>
</body>
</html>