JavaScript在AngularJS控制器之间共享数据

JavaScript在AngularJS控制器之间共享数据,第1张

JavaScript在AngularJS控制器之间共享数据

一个简单的解决方案是让您的工厂返回一个对象,并让您的控制器使用对同一对象的引用:

JS:

// declare the app with no dependenciesvar myApp = angular.module('myApp', []);// Create the factory that share the FactmyApp.factory('Fact', function(){  return { Field: '' };});// Two controllers sharing an object that has a string in itmyApp.controller('FirstCtrl', function( $scope, Fact ){  $scope.Alpha = Fact;});myApp.controller('SecondCtrl', function( $scope, Fact ){  $scope.Beta = Fact;});

HTML:

<div ng-controller="FirstCtrl">    <input type="text" ng-model="Alpha.Field">    First {{Alpha.Field}}</div><div ng-controller="SecondCtrl"><input type="text" ng-model="Beta.Field">    Second {{Beta.Field}}</div>

当应用程序变得更大,更复杂且难以测试时,您可能不希望以这种方式从工厂公开整个对象,而是例如通过getter和setters提供有限的访问权限:

myApp.factory('Data', function () {    var data = {        FirstName: ''    };    return {        getFirstName: function () { return data.FirstName;        },        setFirstName: function (firstName) { data.FirstName = firstName;        }    };});

使用这种方法,由消耗者的控制器来用新值更新工厂,并监视更改以获取新值:

myApp.controller('FirstCtrl', function ($scope, Data) {    $scope.firstName = '';    $scope.$watch('firstName', function (newValue, oldValue) {        if (newValue !== oldValue) Data.setFirstName(newValue);    });});myApp.controller('SecondCtrl', function ($scope, Data) {    $scope.$watch(function () { return Data.getFirstName(); }, function (newValue, oldValue) {        if (newValue !== oldValue) $scope.firstName = newValue;    });});

HTML:

<div ng-controller="FirstCtrl">  <input type="text" ng-model="firstName">  <br>Input is : <strong>{{firstName}}</strong></div><hr><div ng-controller="SecondCtrl">  Input should also be here: {{firstName}}</div>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4938432.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存