angular 1.5 component, ui-router resolve, $onChanges lifecycle hook

折月煮酒 提交于 2019-12-05 11:52:18

Under the hood, UI-ROUTER creates HTML with a one-time binding to $resolve.data on the parent scope.

<app data="::$resolve.data" class="ng-scope ng-isolate-scope">
  <editor on-replace="$ctrl.replace(value)" class="ng-isolate-scope">
    <input type="text" ng-model="value" class="ng-pristine ng-untouched ng-valid ng-empty">
    <button ng-click="$ctrl.replace(value)"> replace object </button>
  </editor>
  <display data="$ctrl.data" class="ng-isolate-scope">
    <p class="ng-binding"> value : initial </p>
  </display>
</app>

The watcher that invokes the $onChanges hook in the app component watches the $resolve.data property of the parent scope. It does not react to changes to the $ctrl.data propery of the isolate scope. And since it is a one-time binding, the $onChanges hook gets invoked only when the variable gets initialized and not on subsequent changes.


Use a Service with RxJZ

Instead of trying to bend $onChange to do something for which it was not designed, build a service with RxJS Extensions for Angular.

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

The DEMO on PLNKR.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!