Ayesha
Ayesha

Reputation: 905

Cannot Read property 'data' of undefined (Angularjs- not able to read data from template to controller)

I am newbie to angularjs. Still understanding the details and how it works. i am in a situation where i cannot find this simple solution. Hope someone could help me here.

I have created a folder structure

Select
->SelectModule.js
->SelectDirective.js
->SelectController.js
->SelectTemplate.html

Here are the contents inside each file.

SelectModule.js

angular.module('Select', []);

SelectDirective.js

'use strict';
angular.module('Select').directive('Select', Select);
function Select() {
return {
    transclude: false,
    scope: {

    },
    controller: 'SelectController',
    templateUrl: 'app/directives/Select/SelectTemplate.html'
};
};

SelectController.js

use strict'
var SelectMod = angular.module('Select', []);
SelectMod.controller('SelectController', function ($scope) {

console.log($scope.details.data);
});

SelectTemplate.html

<section ng-controller="SelectController">
<div><label>Data:</label><div><input type="number" ng-model= "details.data" ng-init="details.data=0.2"  step="0.1" /></div></div>
</section>

Now, in the template i have initialized details.data=0.2. If you see in the controller, i am trying the get this initialized data in templete and outputting it in the console by this statement

console.log($scope.details.data);

The problem is when i run the code and check the console. it gives error stating that "Cannot Read property 'data' of undefined". How do i get this value into the controller. if i get this thing, i will come to know how to get data from template and process in the controller. i am stuck here. someone please suggest or let me know where i went wrong.

Upvotes: 0

Views: 2264

Answers (1)

charlietfl
charlietfl

Reputation: 171690

The reason is the controller has to run before it can render the view, not the other way around.

So at the time you try to log the data it doesn't exist

Don't use ng-init for this purpose. The documentation for ng-init also advises not to use it this way.

Initialize variables in the controller.

Upvotes: 1

Related Questions