angularjs间共享数据

html

<input type="text" ng-model="person.name"/>
  <div ng-controller="FirstCtrl">
  {{person.name}}
  <button ng-click="setName()">set name to jack</button>
  </div>
  <div ng-controller="SecondCtrl">
  {{person.name}}
  <button ng-click="setName()">set name to jack</button>
  </div>
</div>

js

var myApp = angular.module("myApp", []);
myApp.factory('Data', function() {
  return {
    name: "Ting"
  }
});
myApp.controller('FirstCtrl', function($scope, Data) {
  $scope.data = Data;

  $scope.setName = function() {
    Data.name = "Jack";
  }
});

myApp.controller('SecondCtrl', function($scope, Data) {
  $scope.data = Data;

  $scope.setName = function() {
    Data.name = "Moby";
  }
});

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注