大佬教程收集整理的这篇文章主要介绍了angularJS $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”出现在第一个运行时?
谢谢.
请参考以下代码了解工厂:
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 $broadcast和$on全部内容,希望文章能够帮你解决angularJS $broadcast和$on所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。