On loading '/', I am getting 'content' and 'sidebar'using 'myService' and resolve option in route provider and I can render the 'content' to the template ($scope.contents = content;).
But $scope.sideBar = sideBar; is not working. This is because sideBar is outside the template ?
How can I render sidebar items on loading '/' ? Is it possible to pass this data (sidebar) to the indexCtrl?
app.js
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'contents.html',
controller: 'Myctrl',
resolve: {
content: function(myService){
return myService.getContent();
},
sideBar: function(myService){
return myService.getSideBar();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('Myctrl', function (content, sideBar, $scope) {
$scope.contents = content;
$scope.sideBar = sideBar;
});
myApp.controller('indexCtrl', function($scope) {
});
myApp.service("myService", function () {
this.getContent = function () {
return 'Main contents';
}
this.getSideBar = function () {
return 'side bar'
}
});
index.html
<div ng-app="MyApp" ng-controller="indexCtrl">
<div class="sidebar">
{{sideBar}}
</div>
</div>
<div class="main">
<div ng-view></div>
</div>
</div>
contents.html
<div>{{contents}}</div>
You can inject your myService into your indexCtrl and access the function getSideBar like this
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar();
});
this will get the string from your getSideBar function when your indexCtrl is first initialized. If you do this:
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar;
});
and inside index.html:
<div class="sidebar">
{{sideBar()}}
</div>
The string will update when the data in your service updates.
Related
I'm facing problem while initializing a third party JavaScript API (iHUB) inside RUN method of AngularJS. Currently the code is behaving in asynchronous mode. I want IHUB to first initialize and then AngularJS route/controller should get called. (Is it possible to make utilization of the callback method provided by IHUB ?)
var nameApp = angular.module('nameApp', ['ngRoute']);
nameApp.run(['$window', 'myService', function($window, myService) {
//initialize IHUB
var actuate= new actuate();
actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", callback);
function callback(){
alert('started!!');
}
}]);
nameApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:tabname', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'tabDetailCtrl'
}).
when('/:tabname/:reportName', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'reportDetailCtrl'
}).
otherwise({
redirectTo: '/Buy Side Dashboard'
});
}]);
There is only one way to achieve a "real" before AngularJS initialization behavior by using angular.bootstrap();. This allows you to initialize your AngularJS application manually.
Note: You should not use the ng-app directive when manually bootstrapping your app.
> Fiddle demo
View
<div ng-controller="MyController">
Hello, {{greetMe}}!
</div>
Application
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
var actuateDummy = {
initialize: function (callback) {
setTimeout(callback, 2500);
}
};
actuateDummy.initialize(function () {
angular.element(function() {
angular.bootstrap(document, ['myApp']);
});
})
This is an other approach which uses the resolve state of ui-router. This service only initializes iHUB if it not has been initialized yet:
This service also returns the actuate object. In that way you can use it in your controller or components after init.
> Demo fiddle
View
<nav>
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</nav>
<div ui-view></div>
AngularJS Application
var myApp = angular.module("myApp", ["ui.router"]);
myApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state("state1", {
url: "#",
template: "<p>State 1</p>",
controller: "Ctrl1",
resolve: {
iHubInit: function(iHubService) {
return iHubService.init()
}
}
}).state("state2", {
url: "#",
template: "<p>State 2</p>",
controller: "Ctrl2",
resolve: {
iHubInit: function(iHubService) {
return iHubService.init()
}
}
});
});
myApp.controller("Ctrl1", function($scope, iHubService) {
console.log("Ctrl1 loaded.");
});
myApp.controller("Ctrl2", function($scope, iHubService) {
console.log("Ctrl2 loaded.");
});
myApp.service('iHubService', ["$q", function($q) {
this.iHubServiceInitialized = false;
this.actuate = null;
this.init = function() {
if (!this.iHubServiceInitialized) {
//Init
var self = this;
var deferred = $q.defer();
this.actuate = new actuate();
//initialize
this.actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", function() {
self.iHubServiceInitialized = true;
deferred.resolve(self.actuate);
});
return deferred.promise;
} else {
return this.actuate;
}
}
}]);
Try to add a resolve attribute when configuring your route provider like below:
var nameApp = angular.module('nameApp', ['ngRoute']);
nameApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:tabname', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'tabDetailCtrl',
resolve: {
ihubInit: ['iHubService', function (iHubService) {
return iHubService.init();
}]
}
}).
when('/:tabname/:reportName', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'reportDetailCtrl',
resolve: {
ihubInit: ['iHubService', function (iHubService) {
return iHubService.init();
}]
}
}).
otherwise({
redirectTo: '/Buy Side Dashboard'
});
}]);
nameApp.service('iHubService', ["$q", function($q){
this.init = function() {
var deferred = $q.defer();
var actuate= new actuate();
actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", callback);
function callback(){
deferred.resolve();
}
return deferred.promise;
}
}]);
I have one arguments undefined but i don't understand why.
If I put my controller in app.js folder but everything works as I intend to create a good structure nothing works.
structure:
index
app
app.js
components
home
views
job_offers.html
controller
employer_controller.js
My controller:
var app = angular.module('myApp.employerCtrl', []);
app.controller("employerCtrl", ["$scope", function($scope) {
$scope.title = "Fronteend Software Engineer";
$scope.company = "Bee Engineering";
$scope.city = "Lisbon";
$scope.schedule = "Full-time";
$scope.date = "17-10-2016";
console.log($scope.city,$scope.title);
}]);
App.js
var app = angular.module('myApp', ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/",{
templateUrl: "app/components/home/views/job_offers.html",
controller: "employerCtrl"
})
.when("/job" , {
templateUrl: "app/components/job/views/job.html",
controller: "job"
})
.when("/formation" , {
templateUrl: "app/components/formation/views/formation.html",
controller: "formation"
})
.when("/news" , {
templateUrl: "app/components/news/views/news.html",
controller: "news"
})
.otherwise({
redirectTo: '/login'
})
});
html
<html lang="en" data-ng-app="myApp" >
<!-- About Section -->
<section id="slide" class="about-section" >
<div class="container">
<div class="row content" ng-view>
</div>
</div>
</section>
You dont have to declare the module for the controller again,
//remove this line
var app = angular.module('myApp.employerCtrl', []);
app.controller("employerCtrl", ["$scope", function($scope) {
$scope.title = "Fronteend Software Engineer";
$scope.company = "Bee Engineering";
$scope.city = "Lisbon";
$scope.schedule = "Full-time";
$scope.date = "17-10-2016";
console.log($scope.city,$scope.title);
}]);
On the Link below on plunker, I am trying to do a simple page connecting view 1 to view 2.
On view 1 we can type a text which will be shown on View2.
My difficulty is trying to understand how I can connect the Controller1 mentioned in the $stateProviderState, to the
Controller1.js, to the view. I find it difficult to understand how the
factory works, how to do the injection.
Could anyone explain to me? Thank you.
Plnkr - Linking pages using ui-router
//app.module.js
var myApp = angular.module("myApp", ['ui.router']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/View1");
$stateProvider
.state("View1", {
url: "/View1",
templateUrl: "View1.html",
view: {
controller: 'Controller1'
}
})
.state("View2", {
url: "/View2",
templateUrl: "View2.html",
view: {
controller: 'Controller2'
}
});
});
//Controller1.js
(function() {
'use strict';
angular
.module("myApp")
.factory('shareFactory', shareFactory)
.controller('Controller1', Controller1);
function Controller1(shareFactory, $scope, $http) {
var vm = this;
vm.textView1 = "SomethingToStartWith";
function getView1() {
shareFactory.getData()
.then(function(response) {
if (response.data) {
vm.textView1 = response.data;
console.log(vm.textView1);
} else {
console.log("Something was wrong");
return;
}
}, function(response) {
console.log("Entered this Error function");
});
}
}
});
//Index.html
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<script src="https://code.angularjs.org/1.5.5/angular.js" data-semver="1.5.5" data-require="angularjs#1.5.5"></script>
<script data-require="angular.js#<2" data-semver="1.5.7" src="https://code.angularjs.org/1.5.7/angular.js"></script>
<script data-require="ui-router#1.0.0-alpha.5" data-semver="1.0.0-alpha.5" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-alpha.5/angular-ui-router.js"></script>
<script src="app.module.js"></script>
<script src="Controller1.js"></script>
<script src="share.factory.js"></script>
</head>
<body >
<div class="header" ng-style="{background:'red'}">header</div>
<div data-ui-view=""></div>
<div class="footer" ng-style="{background:'blue'}">footer</div>
</body>
</html>
//share.factory.js
(function() {
angular
.module("myApp")
.factory('shareFactory', shareFactory);
function shareFactory() {
var data = '';
return {
getData: function() {
return data;
},
setData: function(newData) {
data = newData;
}
};
}
})();
Maybe code explains itself?
Below code forked from your initial plunk can be found here http://plnkr.co/edit/WLe3TLTa6DKWUQ21lK3P
JavaScript
angular.module('myApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when('', 'view1');
// set up states
// no need to specify controllers in templates
$stateProvider
.state('view1', {
url: '/view1',
templateUrl: 'view1.html',
controller: 'Controller1',
controllerAs: 'vm'
})
.state('view2', {
url: '/view2',
templateUrl: 'view2.html',
controller: 'Controller2',
controllerAs: 'vm'
});
})
// factory, shared data
.factory('shareFactory', function($q) {
var data = 'initial value';
// mock $http using $q which returns
// resolved/rejected promise, as would $http
return {
getData: function() {
return $q.when(data); // resolve
},
setData: function(val) {
if (val.length > 0) {
data = val;
return $q.when(); // resolve
} else {
return $q.reject('value can\'t be empty'); // reject
}
}
};
})
.controller('Controller1', function(shareFactory, $state) {
var vm = this;
// because async
shareFactory.getData()
.then(function(data) {
vm.data = data;
});
vm.set = function(data) {
shareFactory.setData(data)
.then(function() {
vm.error = null;
$state.go('view2');
})
.catch(function(e) {
vm.error = e;
});
};
})
.controller('Controller2', function(shareFactory) {
var vm = this;
shareFactory.getData()
.then(function(data) {
vm.data = data;
})
.catch(function(e) {
console.log(e);
});
});
index.html
<body >
<div data-ui-view></div>
</body>
view1.html
<div>
<h1>view1</h1>
<label>Enter a value: </label>
<input type="text"
ng-model="vm.data">
<input type="button"
class="btn btn-default"
value="Go to view2"
ng-click="vm.set(vm.data)">
<pre ng-bind="vm.error"></pre>
</div>
view2.html
<div>
<h1>view2</h1>
The value set in view1 is: <b ng-bind="vm.data"></b>
<input type="button"
class="btn btn-default"
value="Go to view1"
ui-sref="view1">
</div>
Check the plunker. Injecting factory to controller, controller to main module and ui-routing
Check this
html
<div class="header" ng-style="{background:'red'}">header</div>
<div ui-view></div>
<div class="footer" ng-style="{background:'blue'}">footer</div>
main Js
var myApp = angular.module("myApp", ['ui.router','ConrollerApp']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/View1");
$stateProvider
.state("View1", {
url: "/View1",
templateUrl: "View1.html"
})
.state("View2", {
url: "/View2",
templateUrl: "View2.html"
});
});
Controller
var ctrl=angular.module("ConrollerApp",["Factory"])
ctrl.controller("AppController",function($scope,AppFactory){
$scope.data=AppFactory.useData();
})
Factory
var factoryapp=angular.module("Factory",[])
factoryapp.factory("AppFactory",function(){
return{
useData:function(){
var x=10;
return x;
}
}
})`
I am new to angular JS.How can I redirect to another page when the button is clicked.
My code here
var app = angular.module("plunker", [])
.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/home',
{
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
$routeProvider.when('/about',
{
templateUrl: 'about.html',
controller: 'AboutCtrl'
});
$routeProvider.when('/contact',
{
templateUrl: 'contact.html',
controller: 'ContactCtrl'
});
$routeProvider.otherwise(
{
redirectTo: '/home',
controller: 'HomeCtrl',
}
);
});
app.controller('NavCtrl',
['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'home';
return page === currentRoute ? 'active' : '';
};
}]);
app.controller('AboutCtrl', function($scope, $compile) {
console.log('inside about controller');
});
app.controller('HomeCtrl', function($scope, $compile) {
console.log('inside home controller');
//redirect when button click
function Cntrl ($scope,$location) {
$scope.redirect = function(){
window.location.href = '/about';
}
}
});
app.controller('ContactCtrl', function($scope, $compile) {
console.log('inside contact controller');
});
my html markup is
<div ng-controller="Cntrl">
<button class="btn btn-success" ng-click="changeView('about')">Click Me</button>
</div>
You entered :
How to get this.help me to solve this .
Just use a standard HTML link :
<div ng-controller="Cntrl">
<a class="btn btn-success" ng-href="#/about">Click Me</a>
</div>
No need to create a scope function for that. You can also handle that dynamically thanks to ng-href :
<div ng-controller="Cntrl">
<a class="btn btn-success" ng-href="#/{{view}}">Click Me</a>
</div>
Last thing, you should consider using ui-router which handle even better this cases
Why do you need to send the view as a param:
Try this:
$scope.changeView = function() {
$location.path(#/about);
}
If solution that Cétia presented does not work, then it is possible that you do not have your routes defined. Make sure that you have your route defined withing app.js like this :
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/Login', {
templateUrl: 'Navigate/LoginView',
controller: 'someLoginController'
})
]);
You can as well use angulars state provider (do some research) and from state provider you can access your routes within html as :
<a href="state.routName" />
I have a page in which I want to load three controllers when the user clicks the link retrieve total data, I want the total data view to load three controllers.
I have done the following so far. But it only loads one controller.
HTML
<a href="#/total" > Get Total Data </a></br></br>
<div ng-view style="position: absolute; text-align: left; ">>
</div></p>
</div>
<div>
<script type="text/ng-template" id="test.html">
<h1 class= "tile tileLargo amarelo" >Total Places: {{places.places}}</h1>
<h1 class= "tile tileLargo azul" >Total Users: {{users.users}}</h1>
<h1 >Total Coolios: {{coolios.coolios}}</h1>
</script>
</div>
Angular:
Route:
myApp .config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/total', {
templateUrl: 'test.html',
controller: 'TotalplacesCtrl'
}).
when('/total', {
templateUrl: 'test.html',
controller: 'TotalUserCtrl'
}). when('/total', {
templateUrl: 'test.html',
controller: 'TotalCoolioCtrl'
}).
Contollers:
myApp.controller('TotalUserCtrl', function($scope,$http) {
$http.get('http://94.125.132.253:8001/gettotalusers').success(function (data) {
$scope.users = data;
console.log(data);
}
)}); //Total coolios
myApp.controller('TotalCoolioCtrl', function($scope,$http) {
$http.get('http://94.125.132.253:8001/gettotalcoolios').success(function (data) {
$scope.coolios = data;
console.log(data);
}
)});
//Total coolios
myApp.controller('TotalplacesCtrl', function($scope,$http) {
$http.get('http://94.125.132.253:8001/gettotalplaces').success(function (data) {
$scope.places = data;
console.log(data);
}
)});
How can I fix it? I am very new to angular. But this is what I have done so far.
Only your last route handler will fire in this case as each definition overwrites the last. There's a couple of alternatives I can think of - use the UI Router and use nested states or specify the controller directly on each element that you want to render using that controller... E.g.
Javascript
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/total', {
templateUrl: 'test.html',
controller: 'TotalCtrl'
});
}])
.controller('TotalCtrl', function($scope) {
})
.controller('TotalPlacesCtrl', function($scope) {
$scope.places = {
places: 24
};
})
.controller('TotalUsersCtrl', function($scope) {
$scope.users = {
users: 55
};
})
.controller('TotalCooliosCtrl', function($scope) {
$scope.coolios = {
coolios: 18
};
});
** Template **
<script type="text/ng-template" id="test.html">
<h1 ng-controller="TotalPlacesCtrl">Total Places: {{places.places}}</h1>
<h1 ng-controller="TotalUsersCtrl">Total Users: {{users.users}}</h1>
<h1 ng-controller="TotalCooliosCtrl">Total Coolios: {{coolios.coolios}}</h1>
</script>
Also Plunker to demonstrate.