从服务

时间:2017-07-12 07:31:35

标签: angularjs

我在指令中显示计数器值时遇到问题。

我正在开发一个购物车应用程序,其中我有一个标题指令,只在加载应用程序时加载一次。我有2个链接/按钮的产品列表,用于添加愿望清单和添加到购物车。

情境:

当我在心愿单中添加产品时,我从控制器获取该产品对象并将其发送到服务中,我将该对象推送到服务心愿单数组中。然后我运行一个循环来计算wishlist数组中的对象数量并将其缓存在服务变量中(我没有使用$ rootScope)。我正在使用另一个服务函数来返回此更新的wishlist数组计数。在指令内部,我使用此服务函数来获取更新的计数。

问题:

每次在wishlist数组中添加产品时,wishlist数组都会更新。但它没有在视图中显示更新的值。

1 个答案:

答案 0 :(得分:0)

查看是否要使用服务,然后使用其引用变量,如下所示 Jsfiddle link

js Code

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

  app.controller('ctrl', function($scope, myservice) {
    $scope.data = myservice.data;
    $scope.add = function() {
      myservice.add('test');
    }
  });

  app.controller('ctrl2', function($scope, myservice) {
    $scope.cart = myservice;
  });

  app.directive('myDir', function() {
    return {
      restrict: 'EA',
      template: '<span>my dir Count {{cart.data.length}}</span>'
    }
  });

  app.directive('myDir1', function(myservice) {
    return {
      restrict: 'EA',
      template: '<span>my dir1 Count {{data.get().length}}</span>',
      scope: {},
      link: function(scope) {
        scope.data = myservice;
      }
    }
  });

  app.service('myservice', function() {
    this.data = [];
    this.add = function(item) {
      this.data.push(item);
    };
    this.get = function() {
      return this.data;
    };
    return this;
  });

HTML code

<div ng-app='myApp'>
  <div ng-controller='ctrl'>
    CTRL
    <button ng-click='add()'>
      Add to wishlist
    </button>
    Data :{{data}}
  </div>
  <hr>
  <div ng-controller='ctrl2'>
    Count {{cart.data.length}}
    <br> Count {{cart.get().length}}
  </div>
</div>

通过这种方式,您可以在应用

的任何位置获取服务数据
相关问题