有没有办法让$broadcast在初始化阶段将变量传播给$on?
<div ng-app='test'>
<div ng-controller='testCtrl'> <span>{{testContent}}</span>
</div>
<div ng-controller="testCtrl2">
<input type='text' ng-change="updateContent()" ng-model="testContent2" />
</div>
</div>var app = angular.module('test', []);
app.factory('sharedContent', function ($rootScope) {
var standardContent;
var resizeProportion;
return {
setStandardContent: function (newStandardContent) {
standardContent = newStandardContent;
$rootScope.$broadcast('updateContent');
console.log('broadcast');
},
getStandardContent: function () {
return standardContent;
},
setResizeProportion: function (newResizeProportion) {
$rootScope.$broadcast('updateResizeProportion');
},
}
});
app.run(function (sharedContent) {
sharedContent.setStandardContent('haha');
});
function testCtrl($scope, sharedContent) {
$scope.testContent;
$scope.$on('updateContent', function () {
console.log('receive');
$scope.testContent = sharedContent.getStandardContent();
});
}
function testCtrl2($scope, sharedContent) {
$scope.testContent2 = 'test';
$scope.updateContent = function () {
sharedContent.setStandardContent($scope.testContent2);
};
}样例小提琴:http://jsfiddle.net/jiaming/NsVPe/
跨度将在输入更改时显示值,这是由于ng-change函数所致。
但是,在初始化阶段,值"haha“没有传播到$scope.testContent,因此,在第一次运行时没有显示任何内容。有没有办法让值"haha“在第一次运行时出现?
谢谢。
发布于 2017-07-24 22:11:24
只需使用$timeout函数提供一点延迟即可。只需在工厂中更新代码,它就会开始工作。
请参考以下工厂代码:
app.factory('sharedContent', function ($rootScope,$timeout) {
var standardContent;
var resizeProportion;
return {
setStandardContent: function (newStandardContent) {
standardContent = newStandardContent;
$timeout(function(){
$rootScope.$broadcast('updateContent');
},0)
console.log('broadcast');
},
getStandardContent: function () {
return standardContent;
},
setResizeProportion: function (newResizeProportion) {
$rootScope.$broadcast('updateResizeProportion');
},
}
});发布于 2013-06-05 17:27:40
这样做的原因是,ng-change会在对testContent2标识的模型进行后续更改时触发。当控制器初始化时,会给它赋值"test“。然后,ng-change会跟踪后续更改-初始分配不符合此条件,只有后续更改才符合此条件。
http://jsfiddle.net/vZwy4/ -我更新了你提供的小提琴。在这里,您可以看到span标记正确地填充了数据。
您需要做的是使用作用域的$watch功能,而不是使用ng-change。因此,从输入框中删除ng-change指令并删除updateContent方法。相反,请将其替换为以下代码,您可以在其中观察对testContent2模型的更改:
$scope.$watch('testContent2', function () {
if ($scope.testContent2 === undefined || $scope.testContent2 === null) {
return;
}
sharedContent.setStandardContent($scope.testContent2);
});你现在可以看到"test“这个词(我找不到任何与”haha“有关的东西)在页面加载的那一刻就出现了。对输入的后续更改也会在span中更新。希望这就是你要找的。
发布于 2015-07-08 19:50:08
您没有考虑到的一点是,应用程序的run阶段是在初始化控制器之前执行的。因为广播的消息不会被缓冲,并且只提供给在消息创建时正在侦听的侦听器,所以haha值会丢失。
然而,在您的情况下,通过在控制器中进行一点小的更改就可以很容易地让它工作:
function testCtrl($scope, sharedContent) {
updateTestContent();
$scope.$on('updateContent', updateTestContent);
function updateTestContent(){
$scope.testContent = sharedContent.getStandardContent();
}
}我在这里创建了你的JSFiddle http://jsfiddle.net/y3w5r01d/2/,你可以在控制台上看到每个函数(运行和控制器)何时被执行。
https://stackoverflow.com/questions/16934089
复制相似问题