这就是我现在正在做的事情:http:
//jsbin.com/EDovILI/1/edit
基本上将事件侦听器插入控制器。感觉不是正确的方法,但不确定如何抽象出来
模板:
<div ng-app="app" ng-controller="appController">
<div ng-if="layout == 'big'>...</div>
<div ng-if="layout == 'small'>...</div>
</div>
JavaScript:
function gitReposController($scope, github){
//...
var widthQuery = window.matchMedia("(min-width: 44.375em)");
var setSizeAppropriateTemplate = function (mql) {
if (mql.matches) {
$scope.layout = 'big';
} else {
$scope.layout = 'small';
}
if(!$scope.$$phase) { //prevents it from unnecessarily calling $scope.$apply when the page first runs
$scope.$apply();
}
};
widthQuery.addListener(setSizeAppropriateTemplate);
setSizeAppropriateTemplate(widthQuery);
//...
}
编辑/附录:
在控制器中创建事件侦听器是不好的形式吗?应该改为指令吗?或者也许是一种行为?
编辑:将其修改为指令,并认为它现在更有意义。不过可能会更好。
http://jsbin.com/EDovILI/4/edit
模板:
<div ng-app="gitRepos" ng-controller="gitReposController" breakpoint="min-width: 44.375em">
<div ng-if="matches">...</div>
<div ng-if="!matches'>...</div>
</div>
JavaScript
app.directive("breakpoint", function () {
return function (scope, element, attrs) {
var breakpoint = attrs.breakpoint;
var mql = window.matchMedia( "(" + breakpoint + ")" );
var mqlHandler = function (mql) {
scope.matches = mql.matches;
if(!scope.$$phase) { //prevents it from unnecessarily calling $scope.$apply when the page first runs
scope.$apply();
}
};
mql.addListener(mqlHandler);
mqlHandler(mql);
};
});