【发布时间】:2015-08-05 00:21:30
【问题描述】:
我有一个特定用户的关注按钮,该按钮应在点击后将其文本更改为关注,反之亦然。此关注按钮可以显示在页面上的不同模块中。单击它时,此特定用户的关注按钮应在所有这些模块中更新。但是,按钮在不同的范围内。确保克隆按钮处于相同状态的角度方式是什么?
我目前的解决方案是使用通用 jQuery 选择器来更新所有点击按钮。
【问题讨论】:
标签: html css angularjs state modular
我有一个特定用户的关注按钮,该按钮应在点击后将其文本更改为关注,反之亦然。此关注按钮可以显示在页面上的不同模块中。单击它时,此特定用户的关注按钮应在所有这些模块中更新。但是,按钮在不同的范围内。确保克隆按钮处于相同状态的角度方式是什么?
我目前的解决方案是使用通用 jQuery 选择器来更新所有点击按钮。
【问题讨论】:
标签: html css angularjs state modular
您应该将状态存储在服务中。
示例:
app.factory('SharedService', function() {
this.buttonState = null;
this.setButtonState= function(value) {
this.buttonState = value;
}
this.getButtonState= function() {
return this.buttonState ;
}
return this;
});
【讨论】:
您可以使用$rootScope.$broadcast 来执行此操作。当任何一个按钮被点击时,您使用$rootScope.$broadcast 触发一个事件,然后使用$scope.$on 监听它并切换按钮的状态。您还可以更新service 中的状态,因此您可以稍后在需要时获取当前值。
请看下面的例子:
var app = angular.module('app', []);
app.controller('ctrl1', function($scope) {
$scope.label1 = "First Button";
});
app.controller('ctrl2', function($scope) {
$scope.label2 = "Second Button";
});
app.controller('ctrl3', function($scope) {
$scope.label3 = "Third Button";
});
// updating state in service too.
app.service('fButtons', function($rootScope) {
var buttonState = false;
this.getCurrentState = function() {
return buttonState;
};
this.updateCurrentState = function() {
buttonState = !buttonState;
};
});
app.directive('followButton', function($rootScope, $timeout, fButtons) {
return {
restrict: 'E',
scope: {
label: '='
},
template: '<button ng-click="buttonClick()" ng-class="{red: active}">{{label}}</button>',
controller: function($scope) {
$scope.$on('button.toggled', function() {
$scope.active = !$scope.active;
});
$scope.buttonClick = function() {
fButtons.updateCurrentState();
$rootScope.$broadcast('button.toggled');
console.log(fButtons.getCurrentState());
}
}
};
});
.red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="ctrl1">
<follow-button label="label1"></follow-button>
</div>
<hr/>
<div ng-controller="ctrl2">
<follow-button label="label2"></follow-button>
</div>
<hr/>
<div ng-controller="ctrl3">
<follow-button label="label3"></follow-button>
</div>
</div>
查看控制台了解服务状态。
【讨论】: