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