好的,我知道将观察者放入控制器并不是一个好习惯,但在这种情况下,我怎样才能避免使用观察者?
ps:$ rootscope它不是一个选择吗?
这是代码:
编辑 - 这就是我所做的: plunker
这是js代码:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, mainService) {
var flag = false;
$scope.btn = function () {
flag = !flag;
mainService.setData(flag);
}
});
app.controller('DemoOneCtrl', function($scope, mainService) {
$scope.name = 'World';
$scope.mainService = mainService;
$scope.show = false;
$scope.$watch('mainService.getData()', function (data) {
$scope.show = data;
});
});
app.service('mainService', function () {
var data = false;
this.setData = function (str) {
data = str;
};
this.getData = function () {
return data;
};
});
和html:
<div ng-controller="MainCtrl">
<button ng-click="btn()">GO!</button>
</div>
<div ng-controller="DemoOneCtrl">
<p ng-show="show">Hello World</p>
</div>
答案 0 :(得分:1)
一种方法是将ng-show
绑定到服务功能。
app.controller('MainCtrl', function($scope, mainService) {
var flag = false;
$scope.btn = function () {
flag = !flag;
mainService.setData(flag);
}
});
app.controller('DemoOneCtrl', function($scope, mainService) {
$scope.name = 'World';
$scope.mainService = mainService;
$scope.show = mainService.getData;
});
app.service('mainService', function () {
var data = false;
this.setData = function (str) {
data = str;
};
this.getData = function () {
return data;
};
});
注意$scope.show
如何设置为mainService.getData
。现在,您可以将show()
绑定到ng-show
。
<p ng-show="show()">Hello World</p>
不需要$watch
。