Angularjs – Angular JS : $scope.data is undefined

angularjsangularjs-scopedata-binding

I am new to Angular js. I have tried the following code:

<html>
<head>
    <title>angular js</title>
    <script src="js/lib/jquery.min.js"></script>
    <script src="js/lib/angular.min.js"></script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <input ng-model="data.selected">
    <h1>{{data.selected}}</h1>


    <script>
    var app = angular.module('MyApp',[]);
    app.controller('MyController',function($scope){
        $scope.data.selected = "Initial Text";
    });

    </script>
</body>
</html>

I tried this code to show the initial text in the H1 tag.
But I got the error $scope.data is undefined
What is wrong here? How can I solve this?

Best Solution

This isn't an AngularJS-specific issue, but a general JavaScript error.

in the controller you're accessing the field "selected" of something undefined. try

$scope.data = {}; 
$scope.data.selected="initial text"

or

$scope.data = {selected : "initial text"}; 

http://jsfiddle.net/egamonal/Fn5KF/1/

Related Question