Search code examples
javascriptangularjsangularjs-scopedom-events

AngularJS two-way binding


I am having problems with two-way binding in AngularJS. In my HTML, I have:

<div class="row" ng-app="creation">
    <form class="form-horizontal" ng-controller="CreationController as cCtrl" ng-submit="cCtrl.send()" novalidate>
        <div class="form-group">
            <label class="col-sm-4">Model</label>
            <div class="col-sm-8">
                <input class="form-control" type="text" ng-model="cCtrl['data']['model']" id="model" />
            </div>
        </div>
    ...

On the JavaScript side, I have:

(function() {
    var app = angular.module('creation', ['validation', 'link']);

    app.controller('CreationController', ['$scope', function($scope) {
        $scope.data = {};
        $scope.data.model = 'hello';
    ...

Why is $scope.data.model not displaying hello when I render the HTML page? Instead it is displaying nothing, and when I finally entering something in the input field, it updates $scope.data.model.


Solution

  • This is because you're setting your data model on the $scope but in your html you're referencing under cCtrl which is a controller instance. Try just using ng-model=data.model in your html.