<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/foundation.min.css"/>
<title>Directive与Controller之间的会话</title>
</head>
<body style="padding: 20px;" ng-app="app">
<div ng-controller="AppCtrl">
<div enterattr="delData()">I'm here!</div>
<hello></hello>
<food apple >所有水果</food>
<food orange>苹果</food>
</div>
<script src="js/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('AppCtrl', function ($scope) {
$scope.loadMoreData = function () {
alert("正在加载数据...");
}
$scope.delData = function () {
alert("正在删除数据...");
}
});
app.directive('enterattr', function () {
return function (scope, element, attrs) {
element.bind('mouseenter', function () { //绑定鼠标经过事件
element.addClass('alert-box'); //添加属性
scope.$apply(attrs.enterattr);//获取并执行属性值——delData()函数
})
}
});
app.directive('hello', function () {
return {
restrict: 'E',
template: '<div><input ng-model="txt" ></div><div>{{txt}}</div>',
link: function (scope, element) {
scope.$watch('txt', function (newVal) { //监听txt的值
if (newVal === 'error') {
element.addClass('alert-box');
}
})
}
}
});
app.directive('food', function () {
return {
restrict: 'E',
scope: {}, //清空scope
controller: function ($scope) {
$scope.foods = [];
this.addApple = function () {
$scope.foods.push('apple');
}
this.addOrange = function () {
$scope.foods.push('orange');
}
},
link: function (scope, element, attrs) {
element.bind('mouseenter', function () {
console.log(scope.foods);
});
}
}
});
app.directive('apple', function () {
return {
require: 'food', //引入上面的自定义food组件
link: function (scope, element, attrs, foodCtrl) { //foodCtrl是上面的food的controller控制器
element.bind('mouseenter', function () {
foodCtrl.addApple();
});
}
}
});
app.directive('orange', function () {
return {
require: 'food', //引入上面的自定义food组件
link: function (scope, element, attrs, foodCtrl) { //foodCtrl是上面的food的controller控制器
element.bind('mouseenter', function () {
foodCtrl.addOrange();
});
}
}
});
</script>
</body>
</html>