Re: How can I initialize a variable in controller from a view?

4,256 views
Skip to first unread message
Message has been deleted

Denis Ipatov

unread,
Mar 11, 2014, 10:41:14 AM3/11/14
to ang...@googlegroups.com
How can I initialize a variable in controller from a view (for example fetching in from ASP.NET model)? Something like below:

var app = angular.module("app", []);
app.controller("appCtrl", function ($scope) {
     $scope.myvar;

and in html file:

<div ng-app="app" ng-controller="appCtrl">
  {{myvar = 5}}

Daniel Lidström

unread,
Mar 11, 2014, 10:48:26 AM3/11/14
to ang...@googlegroups.com
Create a service called InitialData. It will return data that you set in razor view. In this way you will have initial data ready for Angular to process once your view has loaded.

Demo online: http://tasksdemo.azurewebsites.net

Hope this helps!

Sander Elias

unread,
Mar 11, 2014, 10:49:36 AM3/11/14
to ang...@googlegroups.com
Hi Denis,

You really need to do this from the view? ng-init will do this for you. However, it is discouraged to do this this way.
What is is you need to do? Perhaps there is a better way to achieve this.

Regards
Sander Elias

Denis Ipatov

unread,
Mar 11, 2014, 10:54:07 AM3/11/14
to ang...@googlegroups.com
Because I'm beginner I need the easist way at this stage to pass a data, just to try AngularJS.

Denis Ipatov

unread,
Mar 11, 2014, 11:04:48 AM3/11/14
to ang...@googlegroups.com
Sander Elias, how exactly I can apply ng-init ? I try use it the third day :-)

Sander Elias

unread,
Mar 11, 2014, 11:05:56 AM3/11/14
to ang...@googlegroups.com

Hi Dennis,

Ah Ok, just keep in mind that this is not the optimal solution, it’s a quick-fix to get you going!

<div ng-controller='myController' ng-init='mydata="test"'>
   <p>mydata contains: {{mydata}}</p>
</div>

Is that enough to get you going?
Regards
Sander

Denis Ipatov

unread,
Mar 11, 2014, 11:15:44 AM3/11/14
to ang...@googlegroups.com
But the problem that in debuger result is: 
  1. xundefined
on my breakpoint here: var x = $scope.mydata;
after this initialization: <div ng-app="app" ng-controller="appCtrl" ng-init="mydata=5">

Sander Elias

unread,
Mar 11, 2014, 11:28:37 AM3/11/14
to ang...@googlegroups.com
Dennis,

Here is a small plunker to show you how it can be done.

Regards
Sander

Denis Ipatov

unread,
Mar 11, 2014, 11:52:22 AM3/11/14
to ang...@googlegroups.com
Hm, vary strange. I tried different combinations with quotes in Visual Studio but no effect.

What the optimal approach to initialize data? Only way is making serviese like in the first topic answer by Daniel Lidström?

Denis Ipatov

unread,
Mar 11, 2014, 12:05:52 PM3/11/14
to ang...@googlegroups.com
And may be I wrong with controller's constraction? Does x variable must be equall to "world"?

app.controller("appCtrl", function ($scope) {
    var x = $scope.mydata; 

Daniel Lidström

unread,
Mar 11, 2014, 12:10:32 PM3/11/14
to ang...@googlegroups.com
Denis, I'm sure it is possible in other ways. However, the service way I suggested has several benefits. It makes a clear separation of what data is coming from backend. It can be used for initialising complex data from backend whereas ng-init is more appropriate for simple initialisation (like editorVisible=false). It is great as a general way of using data from backend without performing a separate request for it. It can be mocked too, of course.

Daniel


--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/LMYhR-CE5Ps/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Sander Elias

unread,
Mar 11, 2014, 12:11:19 PM3/11/14
to ang...@googlegroups.com
Hi Denis,

No that's not the only way, but it's an easy way to get started,
What do you know already of angular? 
you already know something about modules and dependency injection ?

if you have questions about it, don't hesitate to ask!

Regards
Sander

Denis Ipatov

unread,
Mar 11, 2014, 12:36:05 PM3/11/14
to ang...@googlegroups.com
I made another experimet in code:

var app = angular.module("app", []);

app.controller("appCtrl", function ($scope) {
    var x;
    $scope.$watch('myData', function () {
        if ($scope.myData) {
            //here here you can handle your data
            x = $scope.myData;
            console.log('myData:', $scope.myData);
        }
    });
    console.log('my x:', x);

Result is undefined. Why?

my x: undefined app.js:12
myData: world

Kamal

unread,
Mar 11, 2014, 12:55:59 PM3/11/14
to ang...@googlegroups.com
Denis,

Its because $watch is only executed when there is a change in value for the give variable to watch, in this case the ng-init gets executed after the controller (by that time your log of x is already executed) where the value is change there by you see myData as `world`. Simply put `x` and `$scope.myData` are two different variables where `x` is being updated to `$scope.myData` on in case of value change of `myData` using the $watch which is invoked after the controller is initialized by the time your log for x is executed it still undefined as `$scope.myData` is not yet defined/change this happens after when the ng-init is executed. As far as my understanding goes the controller is executed (to initialize the necessary scope) first and later the directive (in this case ng-init). I hope this clarifies it a bit. 

Denis Ipatov

unread,
Mar 11, 2014, 1:37:26 PM3/11/14
to ang...@googlegroups.com
A bit. The world of AngularJS is still seems complicated for some quite trivial tasks :-)


вторник, 11 марта 2014 г., 20:55:59 UTC+4 пользователь Kamal написал:

Owen M

unread,
Mar 11, 2014, 5:09:37 PM3/11/14
to ang...@googlegroups.com
To your original question:
 "How can I initialize a variable in controller from a view (for example fetching in from ASP.NET model)?"

In general treat variables in the template as read only. The overall pattern for this is

View << Responsible for displaying data
<p>Hello {{user.name}}</p>

Controller << Responsible for initializing or hooking up services to be exposed
app.controller("appCtrl", function ($scope, userService) {
  // expose return from service into the scope for the view
  $scope.user = userService.getCurrentUser();
}

Service << Responsible for doing most of the work
app.service("userService", function ($http) {
  return {
    getCurrentUser: function() {
      // using $http or $resource to get the data and return a promise, when resolved will chain all the way up to the view
    }
  }
}

You can set things explicitly in the controller
app.controller("appCtrl", function ($scope) {
  $scope.user = {name: 'Denis', skills: ['Angular', 'HTML', 'CSS']}
}
Generally you only want to do this when setting "basic" variables such as initial UI states. The other case is when you are just experimenting with Angular and fiddling with models and how to display things. Other then that nontrivial models and functions should be placed in services, and hooked into the view via the controller.

A thinking shift with Angular is to embrace promises and scope auto updates. Code as if the data is instantly available, even through you'll be waiting for the server. In the view just write the template {{ myobj.attr }} to be displayed. Controller hooks up the object from the service. When the application first loads myobj won't be there, which is fine, nothing will display. Eventually when the server comes back myobj and attr are set. Since they are on the scope, the $digest cycle will kick in seeing it needs to update. It updates when the data comes back, and everything works. If you need to indicate loading or things that you can use something like: <span ng-hide="myobj.attr">Loading...</span>. When the object is loaded, the ng-hide tag will cause the loading text to disappear for you. I would highly recommend reading about promises and embrace them. It will make your life much easier.

Hope that help,
~Owen 

Denis Ipatov

unread,
Mar 12, 2014, 7:21:01 AM3/12/14
to ang...@googlegroups.com
Many thanx to everybody for helping! Suppose it's time to read AngularJS books and watch videotrainings again.

Denis Ipatov

unread,
Mar 24, 2014, 7:13:02 AM3/24/14
to ang...@googlegroups.com
How can I do the same thing using TypeScript? I mean injecting ASP.NET data to AngularJS controller wrote in TypeScript.
Reply all
Reply to author
Forward
0 new messages