如何 "angular $scope function" 与 "factory"

how to "angular $scope function" with "factory"

我想angular控制器传递参数($scope)

$scope.setName = function() 不起作用,

我该怎么办..拜托~

脚本

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";
  }
});

html

<body ng-app='myApp'>
    <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>
</body>

一切正常。

您打印的是模型而不是服务。

由于服务是在控制器上更改的单例,因此它会针对每个活动的控制器进行更改

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";
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

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