Home Ask Login Register

Developers Planet

Your answer is one click away!

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>
<head lang="en">
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
<body ng-app="graphPlotterDemoApp">

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

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??


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


Leave an answer

Quote of the day: live life