angular js中的控制器之间的数据共享

时间:2019-03-04 07:56:05

标签: angularjs angularjs-service

嗨,我是Angularjs的新手。我正在学习如何使用dataservice在两个控制器之间共享数据。查看该教程,我编写了自己的程序,但没有用。有人可以在这里暗示我在做什么错吗?

<!DOCTYPE html>
<html>
  <head>
    <title>AngularJS Services</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
  </head>
  <body>
    <div ng-app="dataServiceApp">
            <div ng-controller="ChildCtrl">
                    <h2>First controller</h2>
                    <button>+</button>{{Holder.value}}
                  </div>
                  <div ng-controller="ChildCtrl2">
                    <h2>Second controller</h2>
                    <button>+</button>{{Holder.value}}
                  </div>
    </div>
    <script>
        var myapp = angular.module("dataServiceApp",[]);
        myapp.factory('Holder', function() {
  return {
    value: 0
  };
});
myapp.controller('ChildCtrl', function($scope, Holder) {
  $scope.Holder = Holder;
  $scope.increment = function() {
    $scope.Holder.value++;
  };
});

myapp.controller('ChildCtrl2', function($scope, Holder) {
  $scope.Holder = Holder;
  $scope.increment = function() {
    $scope.Holder.value++;
  };
});
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您忘了在按钮上注册onclick侦听器:

<button ng-click="increment()">+</button>{{Holder.value}}

希望这会有所帮助。下面是完整的工作示例:

<!DOCTYPE html>
<html>
  <head>
    <title>AngularJS Services</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
  </head>
  <body>
    <div ng-app="dataServiceApp">
            <div ng-controller="ChildCtrl">
                    <h2>First controller</h2>
                    <button ng-click="increment()">+</button>{{Holder.value}}
                  </div>
                  <div ng-controller="ChildCtrl2">
                    <h2>Second controller</h2>
                    <button ng-click="increment()">+</button>{{Holder.value}}
                  </div>
    </div>
    <script>
        var myapp = angular.module("dataServiceApp",[]);
        myapp.factory('Holder', function() {
  return {
    value: 0
  };
});
myapp.controller('ChildCtrl', function($scope, Holder) {
  $scope.Holder = Holder;
  $scope.increment = function() {
    $scope.Holder.value++;
  };
});

myapp.controller('ChildCtrl2', function($scope, Holder) {
  $scope.Holder = Holder;
  $scope.increment = function() {
    $scope.Holder.value++;
  };
});
    </script>
  </body>
</html>

p.s。我也完全同意JB Nizet的评论:检查您是否真的需要学习AngularJS而不是Angular 2-7 / VueJS / React。