ssm February 2016

binding data in angularJS

So I have this simple controller in app.js

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

app.controller('PlotCtrl1', function ($scope) {
    $scope.data = [{
        x: [1, 2, 3, 4],
        y: [10, 15, 12, 17]}];
});

And I am trying to bind this to a table ...

<!DOCTYPE html>
<html>
<head lang="en">
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="graphPlotterDemoApp">

before div = PlotCtrl1
<div  ng-controller="PlotCtrl1">
    {{data}}
    <table>
    <thead><tr><td>x</td><td>y</td></tr></thead>
    <tbody ng-repeat='x1 in data[0].x'>
        <tr>
            <td><input type='number' ng-model='x1'></td>
            <td><input type='number' ng-model='data[0].y[$index]'></td>
        </tr>    
    </tbody>
    </table>
</div>     
</body>
</html>

It turns out that there is two-way data binding for ng-model='data[0].y[$index] but not for ng-model='x1' !

Anyone knows the reason for this??

Answers


Luka Jacobowitz February 2016

Check out this page in the wiki. https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-repeat

It's all about understanding the difference between objects and primitives when using Angular Scoping.


taystack February 2016

ssm, The data being bound to the $scope is data, right? Unfortunately, you are re-binding a sub-set of data which creates an isolated scope for that specific instance of ng-model. You are trying to bind a new value to the $scope when there was none. It's not the same as saying, ng-model="data", or data[0].y[$index] where you would be directly referring to the original data structure.

Post Status

Asked in February 2016
Viewed 3,582 times
Voted 13
Answered 2 times

Search




Leave an answer