user3177112 user3177112 - 5 months ago 44
Javascript Question

Angular binding to inherited scope variables

I am learning angular and tried to implement dynamic binding on my test page. My goal was to implement input boxes, each one binded to one of dynamically obtained variable name.

If I will not declare results array in root scope - it will create results array for every repetition and under each box I will see it's own results content.

But if I DO decalre results in root scope, and since I do not redeclare it - no shadowing must apply and I should bind each box to variable in root scope's array. But instead I see only root scope's array content under each box, and it does not change, while changing inputs.
Any help appreciated.

Here is my example:

HTML:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="index.js"></script>
<body ng-app="app" ng-controller="main" > <!--ng-init="results = [{'TEST': 1}]" -->

<div>
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
<input type="button" value="Clickme" ng-click="clickfnc()">
<input type="button" value="Dump" ng-click="dump()">
<input type="button" value="Pop" ng-click="remove()">
</div>

<div ng-repeat="x in params">
<p>Name: <input type="text" ng-model="results[x.name]"></p>
<p ng-bind="results[x.name]"></p>
<p>{{x.name}}</p>
<p>{{results}}</p>
<p>{{params}}</p>
</div>

<hr>

<p ng-bind="results"></p>

<hr>

</body>
</html>


index.js:

var app = angular.module('app', []);
app.controller('main', function ($scope)
{
$scope.clickfnc = function ()
{
console.log('click');

$scope.params = [
{
name: 'ACCOUNT'
},
{
name: 'AMOUNT'
}
];
};

$scope.dump = function ()
{
console.log($scope.results)
};

$scope.remove = function ()
{
$scope.params.pop();
}
});

Answer

If I understood correctly what is your goal, the reason you failed that your created results array, but you should create object.
Here: <p>Name: <input type="text" ng-model="results[x.name]"></p>
you assigning new properties to results, so it should be object. You can check this fiddle - https://jsfiddle.net/kb5udcac/