【问题标题】:AngularJS - view not updated when directive changes data in serviceAngularJS - 当指令更改服务中的数据时视图未更新
【发布时间】:2018-12-28 02:34:42
【问题描述】:

我正在使用指令与服务交互,但在显示最新数据的视图时遇到了一些问题。

我设置了以下示例。您可以看到,当控制器与 Service 交互时,视图将使用最新数据进行更新。如果单击指令链接,您可以在控制台中看到数据已更改,但视图未使用该数据更新。

http://jsfiddle.net/kisonay/pv8towqc/

我错过了什么?

JavaScript

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

app.factory('Service', function() {
  var Service = {};
  Service.data = {};
  Service.data.active = false;
  Service.data.one = {};
  Service.data.many = [];
  Service.changeActive = function(state) {
    state = state || false;
    Service.data.active = state;
  };
  Service.setOne = function(one) {
    Service.data.one = one;
  };
  Service.setMany = function(many) {
    Service.data.many = many;
  };
  return Service;
});

app.directive('launcher', function(Service) {
  return {
    restrict: "A",
    link: function(scope, elem, attrs) {
      elem.bind('click', function(event) {
        if (Service.data.active) {
          Service.changeActive(false);
        } else {
          Service.changeActive(true);
        }
        console.log(Service.data); // shows data changed
      });
    }
  };
});

function Ctrl1($scope, Service) {
  $scope.ServiceData = Service.data;
}

function Ctrl2($scope, Service) {
  $scope.active = function() {
    Service.changeActive(true);
  };
  $scope.inactive = function() {
    Service.changeActive(false);
  };
}

HTML

<div ng-controller="Ctrl1">
  {{ServiceData}}
</div>

<hr />

<div ng-controller="Ctrl2">
  Directive: <a href="#" launcher>Change</a>
  <hr /> Controller:

  <button ng-click="active()">
    Active
    </button>
  <button ng-click="inactive()">
    Inactive
    </button>
</div>

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-service


    【解决方案1】:
    app.directive('launcher', function(Service) {
      return {
        restrict: "A",
        link: function(scope, elem, attrs) {
          elem.bind('click', function(event) {
            scope.$apply(function() {
              if (Service.data.active) {
                Service.changeActive(false);
              } else {
                Service.changeActive(true);
              }
            });
          });
        }
      };
    });
    

    【讨论】:

    • 我要感谢您提供的代码示例,但由于它没有解释原因,所以我需要对第一个响应给出正确答案。
    • @kisonay 只要您的问题得到修复就可以了;)
    【解决方案2】:

    你的事件监听器执行了,但 Angular 对它一无所知,所以它不知道它必须检测变化。

    在点击监听的evn处添加scope.$apply();,就可以正常工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      相关资源
      最近更新 更多