angularJS $broadcast和$on

前端之家收集整理的这篇文章主要介绍了angularJS $broadcast和$on前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法让$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”出现在第一个运行时?

谢谢.

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

猜你在找的Angularjs相关文章