Access Angular variable within script tag - javascript

I am making a web app:front-end in Angular and backend in Rails.
I am using LinkedIn's member profile plugin which shows person's profile based on URL being passed. Here is the code for this plugin.
<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/MemberProfile" data-id="(Your LinkedIn URL)" data-format="inline" data-related="false"></script>
I want to make data-id part dynamic. Basically, I will let my users to write their linkedin address in text box and save it to Angular's variable. When the value changes, I want that value gets assigned to data-id. But I'm not sure whether data-id can access a variable in Angular.

Quite simple. Create your app along with a global controller that will be initialised on your html tag like so:
<html ng-app="app" ng-controller="myctrl">
<head>
<script type="IN/MemberProfile" data-id="{{myId}}" data-format="inline" data-related="false"></script>
</head>
</html>
And have this as your controller and app initialisation, or something similar:
var app = angular.module('app', []);
app.controller('myctrl', ['$scope', function($scope){
$scope.myId = 123;
}]);
To break it down, $scope.myId will be assigned the LinkedIn ID, and it is output on the page inside the head tag (I'm guessing that's where you want it) within the data-id attribute on the script tag.
WORKING EXAMPLE

Related

GAE and Angular: How to update data of a HTML JINJA template

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

Load Angularjs controllers in ngView

I'm new to Angular and just started to build a test project to learn it, now have a problem with loading controllers OnDemand.
let's code a bit, I have the following HTML:
index.html
<body>
<div ng-app="MyApp">
CLICK ME
<div ng-view></div>
</div>
<script>
angular.module("MyApp",['ngRoute'])
.config(function($routeProvider) {
$routeProvider.when('/child', {
templateUrl: 'somwhere/child.html',
controller: 'childCtrl' <!-- will remove -->
});
}) <!-- will remove contoller defination below -->
.controller('childCtrl', function($scope) {
$scope.data = DoHeavyCalc();
});
</script>
</body>
what is obvious to me is that I should define my controller exactly where I config my module (MyApp), which doing this depends on DoHeavyCalc() which is not needed right now! (think this method does a big calculation, but it should be run only when the user clicks on the link, not at the beginning of the app).
Now I want to load the and define the controller inside child.html instead of my index.html. OK, so I removed the sections marked in above code and tried to write the child.html like this:
child.html
<div ng-controller="childCtrl">
{{data}}
</div>
<script>
angular.module("MyApp")
.controller('childCtrl', function($scope) {
$scope.data = DoHeavyCalc();
});
</script>
but is causes an error:
[ng:areg] `childCtrl` is not a function. got undefined.
also i tried to put script tag in child.html before the div tag, but it didn't affect anything.
Now my question is, how can i define and load the controller OnDemand and do my heavy work just when the user routes to a certain location not at the beginning of app?
You are asking about lazy loading ! By default angular doesn't support lazy loading, what you can do ? you can use any third party library like requirejs or others.
Currently angularjs doesn't execute any javascript inside templateUrl or template, more details
Here is a working example of lazy loading using requirejs.
Also there is some discussion regarding onDemand script loading
Lazy loading angularjs
In the child.html page do not include ng-controller attribute. Already child.html is associated with the childCtrl controller. Just remove the attribute ng-controller from the child.html page

AngularJS: Access controller properties inside script tag in the view

In app.js I have a controller wrapped in a closure:
(function(){
var app = angular.module('myApp', []);
app.controller('areaInfo', function($http){...});
})()
In index.html, I have:
<body ng-app="myApp" ng-controller="areaInfo as ctrlAreaInfo">...</body>
I have no trouble accessing the controller's properties in HTML between the body tags, but now I need to access its properties within a <script> tag like so:
<body ng-app="myApp" ng-controller="areaInfo as ctrlAreaInfo">
...
<script>
var myVar = ctrlAreaInfo.property;
</script>
</body>
Obviously, the code above doesn't work; so how would I access a controller's property from within a <script> tag?
I ended up using ngMap (https://github.com/allenhwkim/angularjs-google-maps) to display Google Maps and it works like a charm.

AngularJS databinding query

This is a nooob question - as in I started learning Angular today. I was following the tutorial at Angular JS in 30 mins
The idea is to setup basic databinding in Angular. The code displays an input box, and shows(updates) whatever is typed in the box adjacent to it. Coming from a Java world and Spring MVC background, it makes perfect sense as long as the code is as follows:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test Angular</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="maincontroller.js"></script>
</head>
<body>
<div id="content" ng-app="SampleAngular" ng-controller="MainController">
<input type="text" ng-model="inputVal">{{ inputVal }}
</div>
</body>
</html>
app.js
var app = angular.module('SampleAngular', []);
maincontroller.js
app.controller("MainController", function($scope){
$scope.inputVal = "";
}
);
But, the same thing still works if I have a blank body for the controller i.e.:
maincontroller.js
app.controller("MainController", function($scope){
}
);
I understand that I will not be able to get the value of inputVal in the controller but
a) why does it still work in the view?
b) Clearly, I don't have a corresponding model 'inputVal' as defined in ng-model directive, and there are no errors/warnings - which IMHO - is equivalent to failing silently. Is this how Angular is designed? Is this a potential issue in large apps and will make debugging a nightmare?
Thanks in advance.
The following is from the api documentation for ngModel:
Note: ngModel will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope.
Whenever a ng-model is used in the view, corresponding model value is created on the scope of the controller. Angular won't be throwing any error in this case, as this is its default behaviour.
$scope.inputVal = "";
is used more like initialisation of the variable being used.

How to register existing elements with Angular?

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.

Categories