DARK_DUCK
DARK_DUCK

Reputation: 1777

Access "calling scope" and strange behaviour

I have a simple snippet of code :

function SomeCtrl($scope) {
  $scope.modify = function(value) {
    $scope.something = "Hello";
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="SomeCtrl">
    <div ng-repeat="toto in [1,2,4,5]">
      <input ng-model="something" />
      <input ng-model="something" />
      <button ng-click="modify()">Modify</button>
    </div>
  </div>

</div>

Does anyone can explain how I could change it so the modify() function only change the textfields inside the scope of the button I click ?

I also don't get why only the text fields which have not been edited are modified by the function.

Thank you very much

Upvotes: 2

Views: 41

Answers (2)

JanisP
JanisP

Reputation: 1243

In this case you are just pushing out on screen the same info for times, meanwhile binding everything to the same variable. You can just simply create array and bind every input line to appropriate array element. And by pressing "modify" button, pass parameter, witch array element must be changed.

 function SomeCtrl($scope) {
  $scope.something = [];
      $scope.modify = function(toto) {
        $scope.something[toto] = toto;
      };
    }

   

 
         

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        <div ng-app>
          <div ng-controller="SomeCtrl">
            <div ng-repeat="toto in [1,2,4,5]">
              <input ng-model="something[toto]" />
              <input ng-model="something[toto]" />
              <button ng-click="modify(toto)">Modify</button>
            </div>
          </div>
        
        </div>
    
    

Upvotes: 2

user133688
user133688

Reputation: 7064

This is because ng-repeat creates it's own scope. Using prototypal inheritance. By declaring ng-model you're creating a new field on that new scope.

But this will work for what you're trying to do.

 <div ng-repeat="toto in [1,2,4,5]" ng-init="something = {}">
      <input ng-model="something.hi" />
      <input ng-model="something.hi" />
      <button ng-click="modify(something)">Modify</button>
    </div>
  </body>

.controller('ctrl', function ($scope) {
  $scope.modify = function (something) {
    something.hi = "hello";
  }
})

Upvotes: 2

Related Questions