I have a view as
<div class="wrapper" ui-view>
#RenderBody()
</div>
And the state that renderes a template called _BodyLayout is
(function () {
angular.module('ngApp').config(configuration);
configuration.$inject = ['$stateProvider'];
function configuration($stateProvider) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: '/Shared/_Bodylayout',
});
}
})(angular);
I have a run method where the template should register all plugins exactly once for the template when rendered as :
(function () {
'use strict';
angular.module("ngApp").run(run);
run.$inject = ['$rootScope', 'plugin-factory', '$timeout'];
function run($rootScope, plugins, $timeout) {
$rootScope.$on('$viewContentLoaded', function (event) {
plugins.run();
});
}
})(angular);
But on console.log shows that this event runs for multiple times and the plugins.run() method has been called at least 5 times for a single templateURL !!! That makes my sidebar plugin behave weird .
Can anyone tell me why its running 5 times instead of one time for a single templateURL ?
Related
I have a simple application which uses the $stateProvider to toggle between templates/views. I have two links:
Areas
Vendors*
I have the following handler in the controller:
var vm = $scope;
vm.manage = function (type) {
if (type == 'vendors') {
vm.message = 'Comming soon.';
} else {
$state.go(type);
}
};
When I click on the Areas link, I change the state to area (using the $state.go(...) call and then I see the template (and the html contents). Then, when I click the Vendors link I see the default message 'Comming soon'. Then when I click the Areas link again, I get the console.log from the area-controller but not the output (template and the html contents therein). What is going here, this is a very simple task that I do all the time and not sure why I'm not getting the static <h1></h1> the second time I request the $state change.
I have tried $scope.apply() and even $scope = $scope.new assuming somehow something in memory is clogged or something.
My module looks like this:
'use strict';
(function () {
angular.module('areaModule', []).config(areaModule);
areaModule.$inject = ['$stateProvider'];
function areaModule($stateProvider) {
$stateProvider
.state('area', {
url: '/area',
templateUrl: 'app/assetManagement-app/modules/area/area.tmpl.html',
controller: 'area-controller'
});
}
})();
and the controller looks like this
'use strict';
(function () {
angular.module('areaModule').controller('area-controller', areaController);
areaController.$inject = ['$scope', '$state', 'areaService'];
function areaController($scope, $state, areaService) {
var vm = $scope;
// clean up any memory leaks
$scope.$on('$destroy', function () { });
// init()
vm.init = function () {
console.log('area controller');
};
vm.init();
return vm;
}
}());
and the template is here
<div class="container" style="margin: 10px 5px 10px 5px;">
<h1>Area Management View</h1>
</div>
What's going on?
It is a clash between href and state.go. If you remove href in your html It is working as expected.
I have three partial pages in my application and I am using ng-View directive to route to the pages. Also I have separate controller for pages. Now in two of the pages I am making http calls to get / post data, where I am using service to call REST APIs.
Now the problem I am facing every time I am routed to a page, it gets loaded again (executing the function which is making http calls).
In a post like this I saw it is said that this is a default behavior but if so, how can I prevent this to happen. The link I saw is:
The link
Now how can I prevent that to happen, I really do not need to load pages after it is loaded for the first time, when routed.
The code snippets are as follows..
In index.html
To call page link:
...
<md-button class="md-primary" ng-href="#/">Report</md-button>
<md-button class="md-primary" ng-href="#about">About</md-button>
...
<div ng-view></div>
....
In partial1.html, I am not assigning any controller.
In App.js file, setting the route config...
angular
.module('webApp')
.config(function ($routeProvider) {
$routeProvider
.when('/', {
//url: "/report",
templateUrl: 'pages/report.html',
controller: 'ReportController'
})
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
.....
In controller ....
angular
.module('webApp')
.controller('ReportController',
function ($scope, $log, $mdDialog, webAppService) {
var GetReportsFromDB = function () {
webAppService.GetReports().success(function (rptData) {
var dd = JSON.parse(rptData);
rptvm.reports = dd;
}).error(function (response) {
console.log(response);
}).then(function () {
});
};
GetReportsFromDB();
...
In Service ...
angular
.module('webApp')
.service('webAppService', ['$http', function ($http) {
var svc = {};
svc.GetReports = function () {
console.log('loading...');
return $http({
method: 'GET',
url: 'http://somedomain/api/mycontroller/myaction',
});
};
......
I am very new at AngularJS. Any help will be appreciated.
Thanks in advance,
Arpan
Hi iam using Angular with Require.
Require is managing my dependency sequence. Using lazy loading for loading controller and i was able to load my first home controller but when i wanted to navigate to dashboard controller then iam getting error dashboard controller is not found. hereis code
main.html
<body ng-app >
<div id="ViewPort" ng-view> </div>
</body>
shell.js
define(['mngRoute', 'mngSanitize'], function (ngRoute, ngSantize) {
var CMSapp = angular.module('CMS', ['ngRoute', 'ngSanitize']);
CMSapp.config(function ($routeProvider, $httpProvider) {
console.log($httpProvider);
$routeProvider
// route for the home page
.when('/', { templateUrl: 'App/Partials/home.html', resolve: loader(['Home']) })
.when('/Dashboard', { templateUrl: 'App/Partials/Dashboard.html', resolve: loader(['Dashboard']) })
});
CMSapp.run(function () {
console.log('shell loaded');
console.log(CMSapp);
});
return CMSapp;
Home Controller.js
define(function () {
angular.module('CMS').controller('HomeController', ["$scope", "$http", 'MainService', function ($scope, $http, mainService) {
$scope.message = 'Homess';
$scope.InitializeController = function ()
{
console.log(mainService);
mainService.initializeApplication($scope.initializeApplicationComplete, $scope.initializeApplicationError);
}
$scope.initializeApplicationComplete = function (response) {
console.log('in default initializeApplicationComplete');
}
$scope.initializeApplicationError = function (response) {
console.log('in default intialize error');
}
}]);
});
Home.html
<div data-ng-controller="HomeController" ng-init="InitializeController()">
<span>{{message}}</span>
Dashboardcontroller and dashboard.html are same only difference is the name
define(function () {
angular.module('CMS').controller('DashboardController', ["$scope", "$http", 'MainService', function ($scope, $http, mainService) {
$scope.message = 'Dashboard';
$scope.InitializeController = function ()
{
console.log(mainService);
}
}]);
});
Dasboard html
<div data-ng-controller="DashboardController" ng-init="InitializeController()">
<span>{{message}}</span>
i was able to load home and able to bind with model, but this not in dashboard when i entered localhost:8999/Main.html#/Dashboard in url it gives error.
See the chrome console Full console
Angular, Route, Dasboardcontroller.js homecontroller.js shell.js are loaded successfuly no error in console only error is Dasboard controller is not a function, got defined
When you use ng-app, Angular will search for a module called app. If you want to specify a custom module, you need to tell it: ng-app="CMS"
I hope this works! :)
<body ng-app >
should be
<body ng-app="CMS">
because in your code you declare your module as so.
angular.module('CMS'
Chrome console image console2
You can see my app is loaded bootstrapped and controllers are registered as well
I am having a problem with AngularJS, where suddenly one of my controllers refuse to execure.
I load it with route, and i know the route is loaded as the html page attached is requested and inserted into the ng-view div i have.
My routes
when('/products/', {
templateUrl: 'app/components/products/products.html',
controller: 'productsController'
}).
when('/products/:productId', {
templateUrl: 'app/components/products/product.html',
controller: 'productController'
}).
I did not see any problems in my controller so i tried replacing all content with just a simple console log, and yet it do still not execute.
angular.module('DietPlanApp').controller('productsController',
['$scope', function ($scope) {
console.log('Get my products!');
}]);
My other controller productController workes just fine.
angular.module('DietPlanApp').controller('productController',
['$scope', '$routeParams', '$location', 'productService', 'userService',
function ($scope, $routeParams, $location, productService, userService) {
productService.getProduct(userService.getUserToken(), $routeParams.productId, function (data) {
if(data.result) {
$scope.product = transferToPortionSize(data.product);
} else {
$location.path("/products/");
}
});
$scope.save = function () {
productService.save(userService.getUserToken(), transferToUnitSize($scope.product));
$location.path("/products/");
};
$scope.delete = function () {
productService.deleteProduct(userService.getUserToken(), $scope.product.id);
$location.path("/products/");
};
}]);
And i have verified that the js files for productsController is loaded correctly in the HTML head, in the same way productController is.
It looks like the result of a namespace collision. You are overwriting productsController in public/app/components/users/authController.js.
It was probably the result of a copy/paste that your forgot to rename. That seems like the most likely culprit.
See the screenshot here.
I am calling a REST service from angular and it always calls the factory twice. Here is the factory code.
app.factory('dataFactory', ['$http', function ($http) {
var urlBase = '/api';
var dataFactory = {};
dataFactory.getMyItems = function () {
return $http.get(urlBase + '/MyItems');
};
return dataFactory;
} ]);
It's called from the controller here
app.controller('MyItemsController', ['$scope', 'dataFactory',
function ($scope, dataFactory) {
$scope.myItems;
getItems();
function getItems() {
dataFactory.getMyItems()
.success(function (itemsData) {
$scope.myItems = itemsData;
})
.error(function (error) {
$scope.status = 'Unable to load items data: ' + error.message;
});
}
}
]);
I had the same problem as yours where the controller in general was called twice; hence, the factory will be called twice.
But after looking at this solution:
Combating AngularJS executing controller twice
Step 1:
Make sure you are adding the service and controller in your (main layout view) only once.
Example:
index.html
<script src="../MyItemsController.js"></script>
<script src="../MyItemsService.js"></script>
If the problem still persists after doing step 1 go to step 2
Step 2:
There are two ways to do it:-
1. Either keep the controller in your view (ng-controller), and remove it from your config route like this:
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>
2. Or keep the controller in your config route, and remove ng-controller
from view like this:
route config (usually, app.js):
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/',
{
templateUrl: 'pages/home.html',
controller: 'MyItemsController' //Add the controller here
});
}]);
home.html
<!-- Remove the ng-controller in your view -->
<div>
<!-- Your stuff -->
</div>
Note: The above solution works with ui router as well.