What is the best way to access parent scope object from multi-instance directive

时间:2021-07-13 22:59:28

I have directive which can have many instances created in the same parent controller. Directive uses isolated scope with some properties taken from parent scope. One of the directive property can be the callback function which is invoked from directive when directive internal model has changed. If the callback function will change also the model from parent scope which is also assigned to other instance of directive I'm loosing the "connection" between parent scope and directive for this changed model.

我有一个指令,可以在同一个父控制器中创建许多实例。指令使用隔离范围,其中一些属性取自父范围。其中一个指令属性可以是回调函数,当指令内部模型发生更改时,该函数将从指令调用。如果回调函数也将更改来自父作用域的模型,该作用域也被分配给指令的其他实例,我将失去父作用域和此变更模型的指令之间的“连接”。

app.controller('MainCtrl', function($scope) { 
  $scope.manualItem = { };  

  $scope.manualItem.FirstInstanceModel =  "FirstInstance";
  $scope.manualItem.SecondInstanceModel = "SecondInstance";

  $scope.callbackTest = function(newValue){
   $scope.manualItem.SecondInstanceModel = newValue;
  };

});

Directive:

app.directive("multiInstanceControl", [function(){
  return {
    restrict: "A",
    scope: {
      dataModel: "=ngModel",
      dataChangeCallback: "=multiInstanceControlCallback"
    },
    templateUrl: "multiInstanceControlTemplate.html",
    link: function($scope, $element, attr){

      $scope.internalModel = Math.floor(Math.random() * 1000000).toString();//random number generation


      $scope.updateModel = function(){
        $scope.dataModel = $scope.internalModel
      };

    }
  }
}]);

and markup:

 <div 
  multi-instance-control
  ng-model="manualItem.FirstInstanceModel"
  multi-instance-control-callback="callbackTest(manualItem.FirstInstanceModel)"   >
</div>


 <div 
  multi-instance-control
  ng-model="manualItem.SecondInstanceModel">
</div>

Here is the Plunker exmple:

这是Plunker的例子:

In the first input is callback defined when You change it's own value. Callback function is changing model bind to second instance of the directive which is fine in my case. But when You start typing in the second input field, the model is not propagated to parent scope.

在第一个输入中是当您更改自己的值时定义的回调。回调函数正在将模型绑定更改为指令的第二个实例,这在我的情况下很好。但是当您开始键入第二个输入字段时,模型不会传播到父作用域。

The problem is caused by JS prototype inheritance model, but I need to know what is the best way to "share" object between scopes and to handle situation when the object is re-assigned in the parent scope. I'm using angular 1.5.

问题是由JS原型继承模型引起的,但是我需要知道在作用域在父作用域中重新分配时,在作用域之间“共享”对象的最佳方法是什么。我正在使用1.5角。

1 个解决方案

#1


1  

I need to know what is the best way to "share" object between scopes

我需要知道在作用域之间“共享”对象的最佳方法是什么

Use services to share data between controllers.

使用服务在控制器之间共享数据。

Relevant question.

#1


1  

I need to know what is the best way to "share" object between scopes

我需要知道在作用域之间“共享”对象的最佳方法是什么

Use services to share data between controllers.

使用服务在控制器之间共享数据。

Relevant question.