角度工厂服务问题

时间:2016-03-31 18:46:06

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

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

app.js

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

service.js

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

UserController.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

中定义

我可能错过了一些相当基本的东西,但我真的很感激任何帮助。

2 个答案:

答案 0 :(得分:3)

你不能在服务中注入$scope依赖,service/factory是单一对象,它们在角度模块的组件之间共享数据。

将实施更改为以下内容对您有用。

<强>标记

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

答案 1 :(得分:0)

最好这样做。因为“{{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();
      }
   }
]);