【发布时间】:2014-03-28 11:31:30
【问题描述】:
我想创建一个“标题”服务来处理它的标题、按钮和颜色。
主要思想是能够在我的控制器中用一行来自定义这个标题,如下所示:
function HomeCtrl($scope, Header) {
Header.config('Header title', 'red', {'left': 'backBtn', 'right': 'menuBtn'});
}
所以我创建了一个服务(现在我只关注标题):
app.service('Header', function() {
this.config = function(title, color, buttons) {
this.title = title;
}
});
...还有一个指令:
app.directive('header', ['Header', function(Header) {
return {
restrict: 'E',
replace: true,
template: '<div class="header">{{title}}</div>',
controller: function($scope, $element, $attrs) {
$scope.$watch(function() { return Header.title }, function() {
$scope.title = Header.title;
});
}
};
}]);
所以,这确实有效,但我想知道是否没有更好的方法。 尤其是 Header.title 属性上的 $watch。对我来说似乎不是很干净。
关于如何优化这个的任何想法?
编辑:我的标题不在我的视野中。所以我不能直接从我的控制器更改 $scope 值。
Edit2:这是我的一些标记
<div class="app-container">
<header></header>
<div class="content" ng-view></div>
<footer></footer>
</div>
(不确定这段 html 是否会有所帮助,但我不知道哪个部分实际上会......)
谢谢。
【问题讨论】:
标签: angularjs service binding directive