概述
ng-switch可以設置一個開關量,控制子元素顯示情況。ng-switch需要和另外兩個指令:ng-switch-default和ng-switch-when。
實現細節(jié)
指令 | 說明 |
---|---|
ng-switch | 開關指令,可以綁定開關變量,可以配置在ng-switch屬性或者on屬性上 |
ng-switch-default | 默認指令,當開關量沒有匹配時,default指令生效 |
ng-switch-when | 匹配指令,可以關聯(lián)多個值,每一個值用分隔符分隔,由ng-switch-when-separator指定 |
ng-switch實現
在ng-switch指令中會監(jiān)測ng-switch或者on屬性綁定的數據,優(yōu)先使用ng-switch屬性。 ng-switch指令會維護一個map,在這個map中會存放每一個case對應的transclude列表。如果ng-switch的值在map中找到對應的case,就會使用case中存放的transclude列表進行轉換,如果沒有找到,就會使用默認的case。
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
forEach(selectedTranscludes, function(selectedTransclude) {
selectedTransclude.transclude(function(caseElement, selectedScope) {
selectedScopes.push(selectedScope);
var anchor = selectedTransclude.element;
caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
var block = { clone: caseElement };
selectedElements.push(block);
$animate.enter(caseElement, anchor.parent(), anchor);
});
});
}
ng-switch-default實現
default指令會把元素的transclude添加到默認列表中去。
link: function(scope, element, attr, ctrl, $transclude) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: $transclude, element: element });
}
ng-switch-when實現
when指令會把元素的transclude添加到綁定的數據值對應的列表中去。
link: function(scope, element, attrs, ctrl, $transclude) {
var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
// Filter duplicate cases
function(element, index, array) { return array[index - 1] !== element; }
);
forEach(cases, function(whenCase) {
ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
});
}
從代碼可以看出,這個指令主要會進行兩個工作:
1、根據ng-switch-when-separator屬性指定的分隔符分隔ng-switch-when的屬性,并且去除重復數據。
2、循環(huán)遍歷,把自己的transclude添加到對應的case中去。
樣例代碼
<!DOCTYPE html>
<html lang="en" ng-app="app">
<!--<html>-->
<head>
<title>Test</title>
</head>
<body>
<div class="animate-switch-container"
ng-switch on="selection">
<div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
<div class="animate-switch" ng-switch-when="home">Home Span</div>
<div class="animate-switch" ng-switch-default>default</div>
<input ng-model="selection">
</div>
</body>
<script src="./node_modules/angular/angular.js" type="text/javascript"></script>
<script src="./node_modules/angular-sanitize/angular-sanitize.js" type="text/javascript"></script>
<script>
angular.module('app', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.items = ['settings', 'home', 'options', 'other'];
$scope.selection = $scope.items[0];
}]);
</script>
</html>
這段代碼實現了在輸入框中輸入['settings','home','options','other']等值,上方顯示不同的div。