【问题标题】:Issue with angular factory service角度工厂服务问题
【发布时间】:2016-07-20 08:55:10
【问题描述】:

我正在尝试了解 Angular 服务。我创建了一个简单的示例,但是当我尝试使用该服务时,控制台会出现错误(见下文)

app.js

var myApp = angular.module('myApp', []);

service.js

myApp.factory('Addition', function() {
  return {
    plusOne: function() {
      $scope.number += 1;
    }
  };
})

用户控制器.js

myApp.controller( 'UserCtrl', [ '$scope', 'Addition', function($scope, Addition ) {

  $scope.number = 0;

  $scope.plusOne = Addition.plusOne();

}]);

view.html

<div ng-controller="UserCtrl">
     {{number}}

  <button ng-click=plusOne()></button>

</div>

视图正确显示$scope.number,直到我添加$scope.plusOne = Addition.plusOne(); 并且控制台吐出

ReferenceError: $scope 没有在 Object.plusOne 中定义

我可能在这里遗漏了一些相当基本的东西,但非常感谢任何帮助。

【问题讨论】:

    标签: javascript angularjs angularjs-scope angularjs-service angularjs-controller


    【解决方案1】:

    您不能在服务中注入 $scope 依赖项,service/factory 是单例对象,用于在 Angular 模块的组件之间共享数据。

    将实现更改为以下对您有用。

    标记

    <div ng-controller="UserCtrl">
         {{getPlusOneValue()}}
      <button ng-click=plusOne()></button>
    </div>
    

    代码

    myApp.factory('Addition', function() {
      var number = 0;
      return {
        plusOne: function() {
          number += 1;
        },
        //plus one getter
        getPlusOneValue: function(){
           return number;
        }
      };
    })
    

    控制器

    myApp.controller( 'UserCtrl', [ '$scope', 'Addition', 
       function($scope, Addition ) {
          $scope.plusOne = Addition.plusOne;
          $scope.getPlusOneValue = Addition.getPlusOneValue;
       }
    ]);
    

    【讨论】:

    • @dellboyant 很高兴知道这一点..请接受答案..一旦你能做到..谢谢:-)
    【解决方案2】:

    最好这样做。因为“{{getPlusOneValue()}}”函数将在我们不需要的所有角度摘要周期中触发。

    标记

    <div ng-controller="UserCtrl" ng-bind="number">
      <button ng-click=plusOne()></button>
    </div>
    

    工厂

    myApp.factory('Addition', function() {
      var number = 0;
      return {
        //plus one getter
        getPlusOneValue: function(){
           return ++number;
        }
      };
    })
    

    控制器

    myApp.controller( 'UserCtrl', [ '$scope', 'Addition', 
       function($scope, Addition ) {
          $scope.number = '';
          $scope.plusOne = function () {
            $scope.number = Addition.getPlusOneValue();
          }
       }
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多