angularJS $ broadcast和$ on

jia*_*ing 8 angularjs angularjs-scope

有没有办法让$ 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>
Run Code Online (Sandbox Code Playgroud)

 

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);
    };
}
Run Code Online (Sandbox Code Playgroud)

示例小提琴:http://jsfiddle.net/jiaming/NsVPe/

当输入发生变化时,跨度将显示该值,这是由于ng-change功能引起的.

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

谢谢.

cal*_*tie 0

其原因是,该ng-change触发器会在对由 标识的模型进行后续更改时触发testContent2。当控制器初始化时,会为其分配值“test”。ng-change然后跟踪后续更改 - 初始分配不符合此条件,只有后续更改才符合此条件。

http://jsfiddle.net/vZwy4/ - 我更新了您提供的小提琴。在这里您可以看到标签span已正确填充数据。

您需要做的不是使用ng-change,而是应该使用范围的$watch功能。ng-change因此,从输入框中删除指令并删除updateContent方法。相反,请将其替换为以下代码,您可以在其中观察模型的更改testContent2

$scope.$watch('testContent2', function () {
    if ($scope.testContent2 === undefined || $scope.testContent2 === null) {
        return;
    }

    sharedContent.setStandardContent($scope.testContent2);

});
Run Code Online (Sandbox Code Playgroud)

现在,您可以看到页面加载时出现了“测试”一词(我找不到与“哈哈”有关的任何内容)。对输入的后续更改也会在span. 希望这就是您正在寻找的。