gpt4 book ai didi

angularJS $broadcast 和 $on

转载 作者:行者123 更新时间:2023-12-04 08:52:36 29 4
gpt4 key购买 nike

有没有办法让 $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);
};
}

sample fiddle : http://jsfiddle.net/jiaming/NsVPe/

当输入变化时,跨度将显示值,这是由于 ng-change 函数。

但是,在初始化阶段,值“haha”没有传播到 $scope.testContent ,因此在第一次运行时没有显示任何内容。有没有办法让值“haha”出现在第一次运行时?

谢谢你。

最佳答案

只需使用 $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');
},
}
});

关于angularJS $broadcast 和 $on,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16934089/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com