I'm writing an ASP.NET application with AngularJS. I have a value that can only be accessed from the codebehind of a page. I'd like to pass this value down so it can be used by an AngularJS controller. I know it's possible to grab URL parameters for use in AngularJS, but I haven't been able to find any other way of getting a value into my controller. Is this possible?
For example, if I have a setup like this:
<%= user.UserDescription %> <%-- this is how I'd get my value from the codebehind --%>
<div ng-app='myApp' ng-controller='myController1'></div>
...
</div>
I want myController1 to have access to user.UserDescription. It's obviously possible to place the value anywhere on the page, by embedding the C# in the ASP.NET page as you see above, but is it possible to pass it into the controller?
I had a similar issue as I had sever side config that I wanted the client side application to know. The solution I came up with is was a config constant that I would add to the bottom of the page. Then loaded that into my services, etc....
Something like this
<html>
<head>
....
</head>
....
<body>
<script>
(function(){
'use strict';
angular.module('myapp.config',[])
.constant('CONFIG', {
user: {
description: '<%= user.UserDescription %>'
}
});
})();
</script>
</body>
</html>
Related
I am passing parameter to HTML page with NodeJs router using:
res.render('dashboard', {ph_user: fname});
I can use this parameter in my HTML code with:
<div id="greeting">Welcome: <%= ph_user %></div>
However, i also would like to use this parameters with script on HTML page.
I am sure I can extract if from element by ID, but that doesn't seem like the most efficient way. What is the best way, to access/use parameter in script on HTML page.
Any guidance is greatly appreciated.
You can pass the variables like so:
<script type="text/javascript">
var ph_user = <%- ph_user %>;
// or window.ph_user = <%- ph_user %>
</script>
Be sure you understand the differences and risks between escaped and un-escaped variables. You can put this script above your other scripts and then it will be available to the other scripts.
I have a problem with GAE and Angular about updating data dynamically on an HTML template.
What I want is when a new user is inserted into the system it must automatically be shown on the page which lists all the user of the system.
I don't know how to that. I read about Angular and it seems a good framework to update data dynamically on an HTML web page.
I get the page using JINJA and filling the template by querying the NDB datastore where all the Users are stored.
That's the code of the webapp handler which "handles the page":
class TestA(BaseHandler):
def get(self):
template = JINJA_ENVIRONMENT.get_template('templates/Ang2.html')
Users=datastore._retrieve_all_user()
w = self.response.write
w(template.render({'Users': Users}))
When I insert a new user the page with all the Users is shown, meanwhile in another tab the updates aren't shown, but if I refresh the page manually the new user is shown.
So, what I want is obtaining the same result but in automatic way.
The point is I want to refresh periodically the HTML page, in order to show the eventual new users.
So I focused on Angular, and particularly on $interval and $route.reload(), but I have tried to make something which works, but i haven't got anything.
That's the code of the template:
<!doctype html>
<html ng-app="demoApp">
<head>
<title>Hello from a template page!</title>
<link rel="stylesheet" type="text/css" href="/css/helloworld.css">
</head>
<body>
<h1>Hello world HTML template.</h1>
<div data-ng-controller="MyController">
<h3>Elenco utenti:</h3>
<ul>
{% for User in Users %}
<li><b>{{User.username}}</b>: {{User.email}} </li>
{% endfor %}
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var demoApp = angular.module("demoApp", []);
myapp.controller("MyController", function($scope, $interval){
$interval(callAtInterval, 5000);
});
function callAtInterval($route) {
$route.reload();
}
</script>
</body>
Any tips how to do that?
PS: I know the solution isn't elegant, but I chose this solution because I need to know how to do that because it will be useful for next steps of the developing of features of my webapp
Don't refresh the page to update data. Angular was meant to update data without refresh.
Create an API as interface for Datastore operations. Use Angular to execute Promise requests on this API, changing the scope depending on the promise return.
Read the documentation on how angular works first, then learn how to create APIs.
Angular
https://docs.angularjs.org/guide/concepts
API assuming you are using Python
https://www.codementor.io/sagaragarwal94/building-a-basic-restful-api-in-python-58k02xsiq
I am new to Angular JS, I have created a Spring MVC web application with Angular JS, I know that from view we can call REST services from Angular JS using resource, restangular, http , But say in Spring form the Controller a view is been triggered and for loading the datas through angular within the view again a REST call from angular is been called from view to the server and gets the datas thereafter for loading, Instead is there any way to pass the json object while triggering the view from Spring controller to the Angular JS at the first time itself.
I have done a similar thing, its working fine but don't know whether its a good approach or not.
Spring controller
#RequestMapping("/getemployee")
public ModelAndView helloWord(){
JSONArray employeeJsonArray = // contains all the information of the employee
return new ModelAndView("employee", "employee",employeeJsonArray);
}
employee.jsp
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 3.0 MVC Series: Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
$scope.employee = [];
$scope.loadData = function(employee)
{
$scope.employee = JSON.parse(employee);
};
});
</script>
</head>
<body ng-controller="MyCtrl">
{{loadData('${employee}')}}
<input type="text" ng-value="employee[0].name"/>
</body>
</html>
Angular really shines when you use it in a "single" page application, so I would suggest using it as you suggested in your "existing approach" as it moves you closer to a single page app design, however, if you are just trying to get some of the features of Angular in an existing request/response application, then you could send your html payload with the data in ng-init as this page demonstrates. It's a RoR example, but I think the point is clear. I think it is a bit of hack, but should get the job done.
<body ng-init="angularVariable = ${variableFromServer}">
html/angular ...
</body>
I recently switched to using angular, the beauty of it is you can ditch jsp's entirely and just have static html as the frontend. Served as a static resource by spring.
To initially populate your form/tables/whatever - lots of different options do it in javascript/angular. But its nice to keep your view seperate from your controllers (ie don't use jsp's).
You can use below code for get user logging,
<input type="text" ng-model ="currentLoging" ng-init= "currentLoging='${pageContext.request.userPrincipal.name}'" />
Fairly new to Angular and working inside of an existing code base.
Basically, there's an element that exists within the root document (index.html) that already exists in the html before the Angular library loads. Because of this, the ng-click directive isn't registered.
Is there an easy way that I can pass Angular a reference to the element in question and have it register that as one of its own?
Sample code (obviously missing parts, just to illustrate Angular loads after):
<html>
<body ng-app="allMyCookiesApp">
<a ng-click="giveGeuisACookie()">GIMME</a>
<script src="angular.js"></script>
</body>
</html>
I'd like to get a cookie when I click GIMME.
ng-app will bootstrap everything inside it once angular loads. This includes compiling and linking the ng-click in your example. So I think the real problem may be elsewhere.
The biggest omission from this example is any controller. I expect you are missing a controller that can place the giveGeuisACookie method on the correct scope to be used by ng-click. For example
angular.module('allMyCookiesApp', [])
.controller('geuisCtrl', function($scope) {
$scope.giveGeuisACookie = function() {
// Cookie time
};
});
would define your module for ng-app and register a controller for it. This controller will add the giveGeuisACookie function to its scope.
<html>
<body ng-app="allMyCookiesApp" ng-controller="geuisCtrl">
<a ng-click="giveGeuisACookie()">GIMME</a>
<script src="angular.js"></script>
</body>
</html>
tells angular to use the controller so that ng-click will have access to the correct method.
If this is not the problem it may be worth adding a jsfiddle with a working (or not) example of what you are doing.
I got an action result inside a controller and i need to display Modals from bootstrap-modal the problem is... .
ScriptManager.RegisterStartupScript isn't working like in old asp.net
there is a solution to this? I'm new to mvc.
Ok, the easiest solution for registering javascript from the controller was quite obvious, but frustrating for someone who's new to the pattern:
Using named sections we find a place for put the javascript
You can use [Named Sections][1].
_Layout.cshtml
<head>
<script type="text/javascript" src="#Url.Content("/Scripts/jquery-1.6.2.min.js)">
#RenderSection("JavaScript", required: false)
</head>
and this code for the view
_SomeView.cshtml
#section JavaScript
{
#Html.Raw(ViewBag.message)
}
and in the controller we return
ViewBag.message = #"<script type='text/javascript' language='javascript'>alert(""Hello World!"")</script>"; ;
In ASP.NET MVC scripts are not registered in controller actions. There's a separation between controllers and views. So you could directly put the script in the corresponding view: