angularJs-directive之组件复用
单向数据流设计
父作用域type改变,type值传给子作用域的childrenType,改变子作用域的视图。子作用域视图发生改变,emit(‘changeType’, v);通过$emit告诉type改变值,通过type的变化改变视图。数据一定是由父流向子的。
上代码:
scopetest.html
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script>
<script type="text/javascript" src="js/angular-tree-control.js"></script>
<script src="./js/context-menu.js"></script>
<link rel="stylesheet" type="text/css" href="css/tree-control.css">
<link rel="stylesheet" type="text/css" href="css/tree-control-attribute.css">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js"></script>
<script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div ng-controller="father" class="container p-3 mb-2 bg-primary">
<p class="font-weight-bold"> 父作用域:</p>
<div>
<p class="font-weight-bold">
$scope:{'type':{{type}}}
</p>
</div>
<div>
<button type="button" class="btn btn-dark" ng-click="chooseType(1)">展示type1</button>
<button type="button" class="btn btn-secondary" ng-click="chooseType(2)">展示type2</button>
<button type="button" class="btn btn-success" ng-click="chooseType(3)">展示type3</button>
</div>
<div class="container p-3 mb-2 bg-danger" style="margin-top: 20px;">
<view-of-type type="{{type}}" class=""></view-of-type>
</div>
</div>
<script>
const app = angular.module('app', []);
app.controller('father', function ($scope) {
$scope.type = 0;
$scope.chooseType = function (value) {
$scope.type = value;
};
$scope.$on('changeType', function (event, data) {
$scope.type = data;
})
});
app.controller(
'viewOfTypeController', function ($scope) {
$scope.changeFlavor = function () {
let v = parseInt($scope.childrenType);
v = v === 1 ? 2 : v === 2 ? 3 : 1;
$scope.$emit('changeType', v);
}
}
);
app.directive("viewOfType", function () {
return {
scope: {
childrenType: '@type',
},
restrict: "AE",
templateUrl: "viewOfType.html",
controller: 'viewOfTypeController',
link: function (scope, element, attrs) {
}
}
});
</script>
</body>
</html>
组件 viewOfType.html
<div class="card">
<h5 class="card-header">子作用域:</h5>
<div class="card-body">
<p class="card-text" ng-show="childrenType==1"> $scope:{'childrenType':{{childrenType}}}</p>
<p class="card-text" ng-show="childrenType==2"> $scope:{'childrenType':{{childrenType}}}</p>
<p class="card-text" ng-show="childrenType==3"> $scope:{'childrenType':{{childrenType}}}</p>
<button class="btn btn-primary" ng-click="changeFlavor()">click</button>
</div>
</div>