I have a small AngularJS application that use the route feature to render ng-view section. For some reason, the controller and view are not rendering as expected.
This is my application:
angular.module('sitesApp', ['ngRoute']);
var app = angular.module('sitesApp');
app.config(['$routeProvider', function ($routeProvider)
{
$routeProvider.when('/members/sites', {
templateUrl: '/members/_sites',
controller: 'SitesCtrl'
});
}]);
var controllers = {};
controllers.SitesCtrl = function ($scope)
{
alert('SitesCtrl loaded');
}
app.controller(controllers);
My application entry point is "/members/sites". When the user enter this URL, I want that the router will present the file "/members/_sites" in my ng-view.
This is how "/members/sites" looks like:
<div class="container" ng-app="sitesApp">
<ng-view></ng-view>
</div>
<script src="~/Scripts/app/Members/sites-app.js"></script>
This is how "/members/_sites" looks like:
<h1>Hello world!</h1>
Expected: SitesCtrl will be loaded and "Hello world" title will be presented on the screen.
Actual: Nothing. SitesCtrl controller wasn't loaded (no alert executed) and nothing on the screen.
I using angularjs 1.4.9 (with angular-route.min.js).
What the problem of this code?
Related
I am learning Angularjs and having problem with routing. I write up a very simple slim demo example which uses out of the box MVC5. The home page display fine but when I click on the About link it doesn't show the About page and AboutController break point is not hit. And got the following error in Console
Error: [$compile:tpload] Failed to load template: templates/indexView.html (HTTP status: 404 Not Found).
If I swap the two route, then my About page is displayed but got the error when clicking Home link so I am sure the html can be loaded. What do I need to do in order to get the routing to work?
Below is the index.cshtml
#{
ViewBag.Title = "Home Page";
ViewBag.InitModule = "homeIndex";
}
#section Scripts {
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/js/home-index.js"></script>
}
<div data-ng-view=""></div>
Below is the About.cshtml
#{
ViewBag.Title = "About Page";
ViewBag.InitModule = "homeIndex";
}
#section Scripts {
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/js/home-index.js"></script>
}
<div data-ng-view=""></div>
below is the home-index.js
// home-index.js
var module = angular.module("homeIndex", ["ngRoute"]);
var angularFormsApp = angular.module('homeIndex', ["ngRoute"]);
angularFormsApp.config(["$routeProvider",
function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "templates/indexView.html",
controller: "HomeController"
})
.when("/About", {
templateUrl: "templates/aboutView.html",
controller: "AboutController"
});
}]);
angularFormsApp.controller("HomeController",
["$scope",
function ($scope) {
var x = 1;
}]);
angularFormsApp.controller("AboutController",
["$scope",
function ($scope) {
var x = 1;
}]);
The var x=1 has no meaning just for me to set a break point.
Below is indexView.html
<h3>Arrived at Index Page</h3>
aboutView.html
<h3>About Page</h3>
I also have the below in the _Layout.cshtml html tag to hook in angular
data-ng-app="#ViewBag.InitModule"
The problem seems to be that MVC is handling the routing that you expect to be handled by Angular.
Have a look at this question for some more information about having Both AngularJS and MVC in the same project:
Should I be using both AngularJS and ASP.NET MVC?
Here is a nice guide to getting started using the two together, it specifically touches on the routing as well:
Getting started with AngularJS and ASP.NET MVC
I hope that helps, please let us know if you need more information, or if something is not clear.
I am trying to get ng-route working with a google-apps-script web app. I have managed to get basic angular.js functionality working with google-apps-script, but I can't seem to get ng-route to work. I have placed ng-view tags inside a page and have included a separate JavaScript page that contains the routeProvider function.
The ng-view never gets rendered and as far as I can make out the routeProvider does not get called.
Can anyone offer any advice on using ng-route with google-apps-script or suggest another way of rendering a partial html page with google-apps-script
Any answers greatly appreciated.
Have simplified my code and added below:
Code.gs
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
// Build and return HTML in IFRAME sandbox mode.
return template.evaluate()
.setTitle('Web App Window Title')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
index.html
<!-- Use a templated HTML printing scriptlet to import common stylesheet. -->
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<html>
<body ng-app="myApp">
<h1>NG View</h1>
<ng-view></ng-view>
<p>angular check {{'is' + 'working!'}}</p>
<? var url = getScriptUrl();?>
<p id="urlid"><?=url?></p>
</body>
</html>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
Javascript.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-route.js"> </script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider){
console.log('routeProvider config');
var url = document.getElementById("urlid").innerHTML;
console.log('routeProvider config->' +url);
$routeProvider.when("/",
{
templateUrl: url+"?page=_app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
</script>
_app.html
<div>
<h1>{{ app.message }}</h1>
</div>
When this runs angular check {{'is' + 'working!'}} works fine, but the ng-view does not get rendered the java console shows:
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy.
The first obstacle is "sce"
$sce is a service that provides Strict Contextual Escaping services to AngularJS.
Refer link https://docs.angularjs.org/api/ng/service/$sce#trustAsResourceUrl
For the purpose of investigation, I disabled sce (this is not recommended, though)
$sceProvider.enabled(false);
Now the error is shifted to XMLHttpRequest cannot load... No 'Access-Control-Allow-Origin' header is present on the requested resource.
XHR requests to the Google Apps Script server are forbidden
Refer link https://developers.google.com/apps-script/guides/html/restrictions
Google Apps is delivering the files from a different origin than the scripts.google.com and angular js client code is not able to fetch the partial htmls from the same origin.
I guess approach of ng-view is not feasible given the restrictions placed by google apps.
Here is the final modified code
<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider,$sceProvider){
$sceProvider.enabled(false);
console.log('routeProvider config');
var url = document.getElementById("urlid").innerHTML;
console.log('routeProvider config->' +url);
$routeProvider.when("/",
{
templateUrl: url+"?page=_app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
</script>
There has been some time since the question, but I'll post a reply either way.
If your partial html page is not too complicated and big, you can use template instead of templateUrl in the routeProvider, plus create a variable with the html you want to show. Something like this below:
var partial_page = "<span>partial page</span>"
$routeProvider.when("/",
{
template: partial_page,
controller: "AppCtrl",
controllerAs: "app"
}
It worked for me, but I wouldn't advise doing so for a complicated partial page as it may become difficult to read the code
I have a simple service:
angular.module('sf').factory 'sfStatic2', ->
{
doSomething: ->
console.log('called-x')
43
}
angular.module('sf').controller 'UserRegisterCtrl', ($scope,sfStatic2) ->
$scope.timezoneX = sfStatic2.doSomething()
In the console I see two times 'called-x', do you know why is this happening ? I am using angular 1.3.15
This could be occuring due to controller being called two times.
Make sure you are writing controller only once.
write either in ng-controller or in your config route.
route config (usually, app.js):
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/',
{
templateUrl: 'pages/home.html'
//Remove controller from here
});
}]);
home.html
<!-- Add the ng-controller in your view -->
<div ng-controller="MyItemsController">
<!-- Your stuff -->
</div>
I have the following URL:
http://myUrl.com/#/chooseStyle?imgUpload=6_1405794123.jpg
I want to read the imgUpload value in the query string - I'm trying:
alert($location.search().imgUpload);
But nothing alerts, not even a blank alert - but console reads:
$location is not defined
I need this value to add into a controller to pull back data, and also to carry into the view itself as part of a ng-src
Is there anything I'm doing wrong? this is my app config:
capApp.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(false);
$routeProvider
// route for the home page
.when('/', {
templateUrl : '/views/home.html',
controller : 'mainController'
})
// route for the caption it page
.when('/capIt', {
templateUrl : '/views/capIt.html',
controller : 'mainController'
});
}):
This is the view:
<div class="container text-center">
<h1 class="whiteTextShadow text-center top70">Choose your photo</h1>
</div>
<script>
alert($location.search().imgUpload);
</script>
Main controller:
capApp.controller('mainController', function($scope) {
$scope.message = 'Whoop it works!';
});
My end goal is that I can find a solution to capturing and re-using data from the query string.
I will also mention, this is only my first week in Angular, loving it so far! A lot to learn...
<script>
alert($location.search().imgUpload);
</script>
You're making two mistakes here:
executing code while the page is loading, and the angular application is thus not started yet
assuming $location is a global variable. It's not. It's an angular service that must be injected into your controller (or any other angular component). This should cause an exception to be thrown and displayed in your console. Leave your console open always, and don't ignore exception being thrown.
You should not do this
<script>
alert($location.search().imgUpload);
</script>
// you need to inject the module $location
//(either in service, or controller or wherever you want to use it)
// if you want to use their APIs
capApp.controller('mainController', function($scope, $location) {
$scope.message = 'Whoop it works!';
//use API of $location
alert($location.search().imgUpload);
});
I am trying to get a small angularJS app running. The app should receive asynchronous messages via STOMP / Websockets. If a message via the web socket arrives, the angular app is supposed to display a changed value in the UI. In general angular's data binding works as expected, but if the scope is updated within the callback function on_message() nothing happens in the UI. I have read various post on similar topics and tried the suggested solutions like using $apply within the callback function, but without success.
In the debugger I can see that the $scope.SoC gets assigned the correct value, but the UI remains unchanged.
If the function on_message(m) is called directly - just for testing - and not from socket-client, the UI gets updated correctly.
This is the abbreviated structure of the controller code
App.controller('showCaseDataCtrl', function($scope){
var mySoC = 0.7;
$scope.status = {statusMessage: "No Message", SoC: 0.77, power: 5.4, numDevices: 89};
function on_message(m) {
mySoC ++;
$scope.$apply(function() {$scope.status.SoC = mySoC;});
console.log(mySoC);
}
});
This is the HTML
<html ng-app="App">
...
<div class="col-md-4" >
<h1> <span ng-bind="status.SoC" /> SoC</h1>
<p>Charge Status</p>
</div>
...
</html>
Any suggestions what else to try are appreciated.
Update:
The problem has to to with mg-route and a separate view in the main HTML
in the main HTML I am using a statement like
<!-- views selected by the route will be injected here -->
<div ng-view ="" </div>
and the route provider looks like
App.config(function($routeProvider){
$routeProvider
.when('/',
{
controller: 'showCaseDataCtrl',
templateUrl: 'partials/Overview.html'
})
.when('/test',
{
controller: 'showCaseDataCtrl',
templateUrl: 'partials/Overview.html'
})
.otherwise({redirectTo: '/'});
});
Removing the route provider and putting all HTML directly in the main HTML with
<div ng-controller="showCaseDataCtrl" class="col-md-4" >
<h1> <span ng-bind="status.SoC" /> SoC</h1>
<p>Charge Status</p>
</div>
solved the problem.
--- But I have no clue why ---
Any explanation appreciated
The reason the $scope is not updating is because the callback is happening outside of Angular's $digest() cycle. Try wrapping it in $scope.$apply.
function on_message(m) {
// console.log('Received:' + m);
// var MyJSON = $.parseJSON(m.body);
mySoC ++;
$scope.$apply(function() {
$scope.SoC = mySoC;
});
console.log(mySoC);
}
});
Seems like you had it commented out, but that should work.