概述
ng-switch可以設(shè)置一個開關(guān)量区匠,控制子元素顯示情況玷过。ng-switch需要和另外兩個指令:ng-switch-default和ng-switch-when肄鸽。
實現(xiàn)細節(jié)
指令 | 說明 |
---|---|
ng-switch | 開關(guān)指令社证,可以綁定開關(guān)變量钓简,可以配置在ng-switch屬性或者on屬性上 |
ng-switch-default | 默認指令乌妒,當(dāng)開關(guān)量沒有匹配時汹想,default指令生效 |
ng-switch-when | 匹配指令,可以關(guān)聯(lián)多個值撤蚊,每一個值用分隔符分隔古掏,由ng-switch-when-separator指定 |
ng-switch實現(xiàn)
在ng-switch指令中會監(jiān)測ng-switch或者on屬性綁定的數(shù)據(jù),優(yōu)先使用ng-switch屬性侦啸。 ng-switch指令會維護一個map槽唾,在這個map中會存放每一個case對應(yīng)的transclude列表。如果ng-switch的值在map中找到對應(yīng)的case光涂,就會使用case中存放的transclude列表進行轉(zhuǎn)換庞萍,如果沒有找到,就會使用默認的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實現(xiàn)
default指令會把元素的transclude添加到默認列表中去钝计。
link: function(scope, element, attr, ctrl, $transclude) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: $transclude, element: element });
}
ng-switch-when實現(xiàn)
when指令會把元素的transclude添加到綁定的數(shù)據(jù)值對應(yīng)的列表中去。
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私恬、根據(jù)ng-switch-when-separator屬性指定的分隔符分隔ng-switch-when的屬性,并且去除重復(fù)數(shù)據(jù)重虑。
2践付、循環(huán)遍歷,把自己的transclude添加到對應(yīng)的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>
這段代碼實現(xiàn)了在輸入框中輸入['settings','home','options','other']等值永高,上方顯示不同的div。