Noah Stebbins
Noah Stebbins

Reputation: 407

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.

Upvotes: 0

Views: 377

Answers (2)

alexandru.pausan
alexandru.pausan

Reputation: 479

Actually that 'Controller as' syntax can be very useful and easy to follow. I would prefer to keep that because you can isolate the data as you want and work with it in a cleaner way.

The problem with your code is that you have to bind the data object to this, not to the $scope

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

app.controller('CreationController', [function() {
    // You can use an object to refer to *this* (vm stands for 'ViewModel').
    var vm = this;
    vm.data = {};
    vm.data.model = 'hello';
    // or just have vm.data = {model: 'hello'};
...

and then use it in the template like you've used it.

More than that you do not have to inject the $scope** unless you want to use something specific from angular like digest or watch, or inherit from parent scopes/parent controllers.

Here is also a nice style guide for angular that explains other concepts also: Angular Style Guide

Upvotes: 0

r0dney
r0dney

Reputation: 745

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.

Upvotes: 2

Related Questions