I am using templateUrl to display specific php pages in my webpage. Now I wish to scrap the individual php pages and display code with variables passed to it. What is the easiest way to get back to this?
var AppModule = angular.module('App', ['ngAnimate', 'ngRoute']);
AppModule.config(function($routeProvider) {
$routeProvider
.when('/page:pageNumber', {
templateUrl: function ($routeParams) {
return '/app/..../assets/html/page' + $routeParams.pageNumber + '.php';
},
controller: "PageCtrl"
})
.otherwise({
redirectTo: "/page1"
});
});
AppModule.controller("ViewCtrl", function($scope, $timeout) {
$scope.$on("$routeChangeSuccess", function(event, current, previous) {
...stuff...
});
});
Use scripts via text/ng-template, which allows you to write your templates inline while declaring a url to access them by. The following code can go directly in your index.html, and if your config is set to show '/my-template.html', the inline template will be output right in the ng-view above it.
<ng-view />
<script type="text/ng-template" id="/my-template.html">
template goes here
</script>
Then in your config:
.when('/', {
templateUrl: '/my-template.html'
});
Here's a little more info from the Angular docs:
https://docs.angularjs.org/api/ng/directive/script
And lastly, this technique is demonstrated in one of the TodoMVC examples for Angular:
View: https://github.com/tastejs/todomvc/blob/gh-pages/examples/angularjs/index.html
Config: https://github.com/tastejs/todomvc/blob/gh-pages/examples/angularjs/js/app.js
Related
I'm very new to Angular.js.
I've taken the necessary elements from this tutorial on modal windows within Angular.js: http://jasonwatmore.com/post/2016/07/13/angularjs-custom-modal-example-tutorial
Isolated, I can get this code to work, but after porting it to my website, I just can't get it to work.
In Jason's code, he has a file called index.controller.js, and although I've ported this file to my own page, I don't believe it's firing. Here's index.controller.js:
(function () {
angular
.module('app')
.controller('Home.IndexController', Controller);
function Controller(ModalService) {
var vm = this;
vm.openModal = openModal;
vm.closeModal = closeModal;
function openModal(id){
ModalService.Open(id);
}
function closeModal(id){
ModalService.Close(id);
}
}
})();
On my own page, I have all the controllers contained within app.js. Here's how it's laid out:
var app = angular.module('app', ['ngRoute', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'pages/main.html',
controller: 'mainController',
controllerAs: 'vm'
})
.state('screenings', {
url: '/screenings',
templateUrl: 'pages/screenings.php',
controller: 'Home.IndexController',
controllerAs: 'vm'
})
...
});
You can see that, in the second .state, I'm attempting to call on the index.controller.js file for this particular partial. For some reason, though, the code under screeningsController (down below) is the code that's firing.
Further down in the same app.js file, I have my controllers:
...
app.controller('screeningsController', ['$scope', '$log', function($scope, $log){
$scope.popup = function() {
// assign a message to the $scope
$scope.message = 'Hello World!';
// use the $log service to output the message in a console
$log.log($scope.message);
};
}]);
...
Is there any way I can somehow integrate what's in the index.controller.js file into my screeningsController in the app.js? I've been trying to get a modal window working on my site for about a week now. Any help is much appreciated.
Start by creating a controller with identifier Home.IndexController. Based on the route configuration this will instantiate when you navigate to "/screenings". Call the popup() function attached to $scope of Home.IndexController via a directive us ng-click for testing. As you have specified controllerAs make sure to reference controller properties and methods prefixed with vm..
You do not need both index.controller.js and app.js both loaded. It looks everything you'd need is defined in app.js, so just make sure that is being loaded in your application. Eventually you'd want to separate these into different files and/or modules as necessary.
Try the following:
Configuration:
var app = angular.module('app', ['ngRoute', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'pages/main.html',
controller: 'mainController',
controllerAs: 'vm'
})
.state('screenings', {
url: '/screenings',
templateUrl: 'pages/screenings.php',
controller: 'Home.IndexController',
controllerAs: 'vm'
});
...
});
Home.IndexController:
app.controller('Home.IndexController', ['$log', function($log){
var vm = this;
vm.message = '';
vm.popup = function() {
vm.message = 'foobar';
$log.log(vm.message);
}
}]);
Screenings Template:
<!-- Home.IndexController /screenings template -->
<div>
<button type="button" ng-click="vm.popup()"></button>
</div>
This also assumes you have ui-view specified somewhere in your main template like index.html or equivalent:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body ng-app="app">
<div ui-view></div>
<!-- Vendor and Custom scripts added here -->
</body>
</html>
I am using two app modules in this app. Why do I get this error? I define the navCtrl in my index.html file where ng-view is like this:
<body ng-app="ciscoImaDashboardApp" ng-controller="navCtrl">
Error: [ng:areq] Argument 'navCtrl' is not a function, got undefined
What am I doing wrong? Am I getting this because I define angular.module in all my js files?
Routes JS:
angular.module('ciscoImaDashboardApp', ['ciscoImaDashboardAdmin', 'ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/admin', {
templateUrl: 'views/admin.html'
})
.when('/', {
templateUrl: 'views/welcome.html',
controller: 'welcomeCtrl'
})
.when('/overall-results', {
templateUrl: 'views/overall.html',
controller: 'overallCtrl'
})
.when('/swim-lane-results', {
templateUrl: 'views/swim-lane.html',
controller: 'swimlaneCtrl'
})
.when('/key-exemplifiers', {
templateUrl: 'views/key-exemplifiers.html',
controller: 'petalCtrl'
})
});
Second Module:
angular.module('ciscoImaDashboardAdmin',[])
.controller('minisCtrl', function ($scope) {
});
Nav JS:
angular.module('ciscoImaDashboardApp',['ciscoImaDashboardAdmin'])
.controller('navCtrl', function($scope, navService, $location, dummyData) {
});
right way :
angular.module('ciscoImaDashboarAdmin')
.controller('minisCtrl', function ($scope) {
});
remove dependency practice in the second time
from angular js documentation you can find below block check the link here
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other.
http://jsfiddle.net/4nil/puw6huv4/
Here,
I am trying to inject ngroute dependency
var sampleApp = angular.module("sampleApp", ["ngRoute"]);
and trying to use routeprovider as below
sampleApp.config(["$routeProvider",
function($routeProvider) {
$routeProvider.
when("/addRomCom", {
templateUrl: "add_book.html",
controller: "romcomctrl"
}).
when("/addHorror", {
templateUrl: "add_book.html",
controller: "horrorctrl"
}).
otherwise({
redirectTo: "/"
});
}]);
The same code works in a standalone application, i have only one html which has script tag which has the code.
The issue with your fiddle is the loading of your js. right now you are loading it in onLoad
Go to the javascript section settings and change the load type to : No Wrap in <body>
EDIT:
if you put it on load, the code would be local to the onLoad scope, and it would not be visible outside globally, so ng-app="myApp" would not be able to recognize the module because
var myApp = angular.module("myApp", [] ) ; lives only inside the onLoad function.
I am trying to create an Angular Dynamic Routing. My routing is like this:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: 'partials/blank.html' });
$routeProvider.when('/:name', { templateUrl: 'partials/blank.html', controller: PagesController });
$routeProvider.otherwise({redirectTo: '/'});
}]);
Here I am using $http to get a template file inside a controller and compile it to a div id like this:
function PagesController($scope, $http, $route, $routeParams, $compile) {
$route.current.templateUrl = 'partials/' + $routeParams.name + ".html";
$http.get($route.current.templateUrl).then(function (msg) {
$('#view-template').html($compile(msg.data)($scope));
});
}
In the template view, I have a div like this:
<div id="view-template" ng-view></div>
I thought the above code will compile and add the html data to the div but I am receiving the error that says: $ is not a function. What have I got wrong here?
EDIT: After the help from the comments and answers below
SOLUTION:: I was playing around with this a bit more and I went with another solution for this. I added the $route.current.templateUrl to the $scope.theTemplateUrl and then used ng-include in the template file. That did the trick and I also dont need to use the jquery $ function to manipulate the DOM.
Please make a fiddle. The limited scope of this snippet inhibits help :)
By just looking at what you are doing I can only make a few recommendations. But I think your issue lies in .html().
Stop using jQuery while you learn Angular.
Use $scope to change content on page. Instead of
$('#view-template').html($compile(msg.data)($scope));
do this
$scope.viewTemplate = msg.data
then use angular in your view :)
Only use the controller to coordinate the flow of information. There should not be and DOM manipulation happening here. The DOM should reflect a state of the controller.
Define routes in your app config. This is not correct.
$route.current.templateUrl = 'partials/' + $routeParams.name + ".html";
I have some example site in my github repo that you can look at if you want to see a few full sites working: https://github.com/breck421
It seems like you have missed some key parts of Angular. Make sure you take your time and learn it right. It will make you life much easier later.
Thanks,
Jordan
Added for a route provider example:
MyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'js/views/index.html',
controller: 'AppController',
activeTab: 'home'
})
.when('/home', {
templateUrl: 'js/views/index.html',
controller: 'AppController',
activeTab: 'home'
})
.when('/thing1', {
templateUrl: 'js/views/thing1.html',
controller: 'Thing1Controller',
activeTab: 'thing1'
})
.otherwise({redirectTo: 'home'});
}]);
Then use links like this: Components
EDIT Adding a compile directive per request:
angular.module('CC.directive.Compile', [], function($compileProvider) {
$compileProvider.directive('compile', ['$compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.compile);
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
}]);
});
The $ function is defined by jQuery, not angular. Make sure that you have included the jQuery library in order to use $
After the Angular app is loaded I need some of the templates to be available offline.
Something like this would be ideal:
$routeProvider
.when('/p1', {
controller: controller1,
templateUrl: 'Template1.html',
preload: true
})
This is an addition to the answer by #gargc.
If you don't want to use the script tag to specify your template, and want to load templates from files, you can do something like this:
myApp.run(function ($templateCache, $http) {
$http.get('Template1.html', { cache: $templateCache });
});
myApp.config(function ($locationProvider, $routeProvider) {
$routeProvider.when('/p1', { templateUrl: 'Template1.html' })
});
There is a template cache service: $templateCache which can be used to preload templates in a javascript module.
For example, taken from the docs:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
There is even a grunt task to pre-generate a javascript module from html files: grunt-angular-templates
Another way, perhaps less flexible, is using inline templates, for example, having a script tag like this in your index.html:
<script type="text/ng-template" id="templates/Template1.html">template content</script>
means that the template can be addressed later in the same way as a real url in your route configuration (templateUrl: 'templates/Template1.html')
I think I have a slightly improved solution to this problem based on Raman Savitski's approach, but it loads the templates selectively. It actually allows for the original syntax that was asked for like this:
$routeProvider.when('/p1', { controller: controller1, templateUrl: 'Template1.html', preload: true })
This allows you to just decorate your route and not have to worry about updating another preloading configuration somewhere else.
Here is the code that runs on start:
angular.module('MyApp', []).run([
'$route', '$templateCache', '$http', (function ($route, $templateCache, $http) {
var url;
for (var i in $route.routes) {
if ($route.routes[i].preload) {
if (url = $route.routes[i].templateUrl) {
$http.get(url, { cache: $templateCache });
}
}
}
})
]);
Preloads all templates defined in module routes.
angular.module('MyApp', [])
.run(function ($templateCache, $route, $http) {
var url;
for(var i in $route.routes)
{
if (url = $route.routes[i].templateUrl)
{
$http.get(url, {cache: $templateCache});
}
}
})
if you wrap each template in a script tag, eg:
<script id="about.html" type="text/ng-template">
<div>
<h3>About</h3>
This is the About page
Its cool!
</div>
</script>
Concatenate all templates into 1 big file. If using Visual Studio 2013,Download Web essentials - it adds a right click menu to create an HTML Bundle
Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works :-)
https://gist.github.com/vojtajina/3354046
Your routes templateUrl should look like this:
$routeProvider.when(
"/about", {
controller: "",
templateUrl: "about.html"
}
);