Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop two way databinding on model

I'm fairly new to Angular so if there is some incorrect thinking here, please let me know.

I'm trying to create two separate scope variables based on the same data set. I assumed that I would just be able to set them to different variables (as shown below) and it would work. I've found, however, that no matter what they are named or how they are defined (even in a directive!) that changing one changes them all.

So...what I expect/would like to see is that if I change the input in the top repeat it will only change the model for that repeat. Currently it changes all three.

Where am I going wrong here? I assume this has something to do with the two way data-binding. Thanks in advance!

Plnkr

HTML:

 <h4>data</h4>
    <div ng-repeat="person in data">
      {{person.name}}
      <input ng-model="person.name" />
    </div>
    {{data[0].name}}
    <br>
    <br>

    <h4>testData</h4>
    <div ng-repeat="person in testData">
      {{person.name}}
      <input ng-model="person.name" />
    </div>
    {{testData[0].name}}

    <h4>Directive</h4>
    <div tester data="data"></div>

Directive HTML:

<div ng-repeat="person in data">
  {{person.name}}
  <input ng-model="person.name" />
</div>
{{data[0].name}}

JS:

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

(function () {

    var testController = function ($scope) {

      var data = [
        {name:'Jordan', age:30},
        {name:'Sean', age:32},
        {name:'Seth', age:26}
      ];

      $scope.data = data;

      $scope.testData = data;
    }    

    testController.$inject = ['$scope', '$http'];

    app.controller('testController', testController);


}())

app.directive('tester', function(){
    return {
        restrict: 'A',
        templateUrl: 'directive.html',
        //If percent = true then that table should have a "percent change" th
        scope:{
            data: '=data'
        }
    }

})
like image 823
Aarmora Avatar asked Nov 28 '22 01:11

Aarmora


1 Answers

I'm trying to create two separate scope variables based on the same data set. I assumed that I would just be able to set them to different variables (as shown below) and it would work

Actually both those javascript variables are pointing to the same data structure in memory. So when you modify this structure it reflects to both of them. Think of those data and testData variables as pointers to the same data.

You could copy this data structure in order to create 2 different instances of it in memory so that changes to one do not reflect to changes of the other:

$scope.data = data;
$scope.testData = angular.copy(data);

and if you wanted to reflect this in your directive, go ahead and clone the instance you are passing to it as well:

<div tester data="angular.copy(data)"></div>
like image 155
Darin Dimitrov Avatar answered Dec 05 '22 00:12

Darin Dimitrov