When trying to redirect to an external page using $window.location.href, the page is just refreshing and not redirecting to the expected URL.
<html ng-app="myApp">
<head>
</head>
<body ng-controller="myCtrl">
<p> <button>Click me to redirect from template</button></p>
<p ng-click="myFunction()"> <button>Click me to redirect from controller</button></p>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($window,$scope){
$scope.myFunction = function(){
$window.location.href = 'http://www.google.com'; //You should have http here.
}
});
</script>
</body>
</html>
This works for me.
pdmApp.controller('projectionDetailController', [ '$log', 'projectionDetailService', '$filter', '$window', '$location', '$scope', function ($log, pdService, $filter,$window,$location, $scope) {
$scope.backToPreviousPage = function () {
alert("function is working"); //Add this line to your code to confirm your function is called.
$window.location.href = "http://localhost:port/../sample2.aspx";
}
} //What is this bracket for?
}]); //you are missing this square bracket.
Change To
pdmApp.controller('projectionDetailController', ['$log', 'projectionDetailService', '$filter', '$window', '$location', '$scope', function($log, pdService, $filter, $window, $location, $scope) {
$scope.backToPreviousPage = function() {
alert("function is working"); //Add this line to your code to confirm your function is called.
$window.location.href = "http://localhost:port/../sample2.aspx";
};
]);
Related
I need to call function in another controller in AngularJS. How it is possible? I used below code but it's not working.
EmployeeCtrl
routerApp.controller('EmployeeController', function ($scope, $rootScope) {
$rootScope.$on("CallSearchtMethod", function (searchName) {
$scope.parentmethod(searchName);
});
$scope.parentmethod = function (searchName) {
console.log("data is" + searchName);
}
}
})
NavCtrl
routerApp.controller('navCtrl', function ($scope,$rootScope ) {
$scope.searchFun = function (searchName) {
$rootScope.$emit("CallSearchtMethod", searchName);
}
})
You should use Service. What it does is that it allows you to create common functions that will be used in many places, which in this case are controllers.
Here is an example working code snippet that will guide you to do the Service.
angular.module('starterByAR', ['starterByAR.controllers', 'starterByAR.services']);
angular.module('starterByAR.controllers', [])
.controller('mainOne', [
'$scope', 'myService',
function($scope, myService) {
$scope.text = myService.commonFunction();
}
])
.controller('mainTwo', [
'$scope', 'myService',
function($scope, myService) {
$scope.text = myService.commonFunction();
}
]);
angular.module('starterByAR.services', []).service('myService', function() {
return {
commonFunction: function(){
return 'Some Text';
}
};
});
<head>
<title>Angular Starter</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-app="starterByAR">
<div ng-controller="mainOne">
Here is {{text}} from Controller 1
</div>
<div ng-controller="mainTwo">
Here is {{text}} from Controller 2
</div>
</body>
I have this js code
var app = angular.module('app', []);
app.service('testService', function(){
this.sayHello= function(text){
return "Service says \"Hello " + text + "\"";
};
this.sayGoodbye = function(text){
return "Service says \"Goodbye " + text + "\"";
};
});
app.controller('AboutCtrl', ['testService', function ($scope, $location, $http) {
$scope.fromService = testService.sayHello("World");
$scope.toService = testService.sayGoodbye("World");
}]);
and in my html I have this
....
...
hi {{fromService}}
....
...
There are no errors in console and the page is just blank.
Please take a look at AngularJs Docs "Using Dependency Injection".
The correct way:
app.controller('AboutCtrl', ['$scope', '$location', '$http',
'testService', function ($scope, $location, $http, testService) {
$scope.fromService = testService.sayHello("World");
$scope.toService = testService.sayGoodbye("World");
}]);
You can inject your service to controller by these ways.
Inline Array Annotation
app.controller('MyController', ['$scope', 'testService', function($scope, testService) {
// ...Code here
}]);
$inject Property Annotation
var MyController = function($scope, testService) {
// ...
}
MyController.$inject = ['$scope', 'testService'];
app.controller('MyController', MyController);
Implicit Annotation
app.controller('MyController', function($scope, testService) {
// ...
});
if you want to know which one is preferred then read this Dependency Injection
You're not injecting your service properly.
app.controller('AboutCtrl', ['$scope', '$location', '$http',
'testService', function ($scope, $location, $http, testService) {
$scope.fromService = testService.sayHello("World");
$scope.toService = testService.sayGoodbye("World");
}]);
Also in your HTML you should add ng-app="app" and ng-controller to especify your controller.
<!DOCTYPE html>
<html ng-app="app">
<head></head>
<body ng-controller="AboutCtrl">
<p>Hi {{fromService}}</p>
<!-- Also place here your JS files.-->>
</body>
</html>
Supper easy, Actually you are injecting service wrong place check this:
app.controller('aboutCtrl', function ($scope, $location, $http, testService) {
$scope.fromService = testService.sayHello("World");
$scope.toService = testService.sayGoodbye("World");
});
I have a controller called UserCtrl and it depends on a service called UserService. When the view that uses the controller UserCtrl loads I get an error:
Unknown provider: UserServiceProvider
Here is my service code:
angular.module('UserService', []).service('UserService', ['$rootScope', '$route', '$http', '$filter', function ($rootScope, $route, $http, $filter) {
function loadType() {
var deferred = $q.defer();
$http.get('json/type.json').success(function (response) {
var typeoflaw = response;
}).error(function (status, data) {
console.log("error trapped");
});
deferred.resolve(typeoflaw);
return deferred.promise;
};
}]);
Here is my controller code:
JBenchApp.controller('UserCtrl', ['$scope', '$routeParams', '$http', '$filter', 'UserService',
function ($scope, $routeParams, $http, $filter, UserService) {
// Get the preferences information
UserService.loadType()
.then(function (lawtypes) {
$scope.typeoflaw = lawtypes;
});
$scope.SavePreferences = function () {
};
}]);
What did I do wrong?
EDITED TO SHOW JBenchApp code:
var JBenchApp = angular.module('JBenchApp', [
'ngRoute',
'UserService'
]);
This brings to mind a question that has bugged me. What order do you declare your JS files for angular in the index.html page? Mine are currently:
<script src="../js/angular.min.js"></script>
<script src="../js/angular-route.min.js"></script>
<script src="../js/app.js"></script>
<script src="../js/services.js"></script>
<script src="../js/controllers.js"></script>
<script src="../js/directives.js"></script>
May be try this
angular.module('UserService').controller('UserCtrl', ['$scope', '$routeParams', '$http', '$filter', 'UserService',
function ($scope, $routeParams, $http, $filter, UserService) {
//controller code here
}]);
I am using
<div ng-controller="DailyReportsController">
<iframe ng-src="{{content}}" style="width:100%;height:100%;"></iframe>
</div>
to include 'pdf' file in html page. The corresponding controller is given below
mainApp.controller('DailyReportsController',
['$scope', '$state', '$rootScope', 'mainWebService', '$http', '$sce',
function($scope, $state, $rootScope, mainWebService, $http, $sce) {
angular.element(document).ready( function() {
var drtab = new Royal_Tab($('.dailyrpts_tabs.royal_tab'));
$scope.content =$sce.trustAsResourceUrl("https://gcc.geojit.net/researchdesk/OPTION STRATEGIES2.pdf");
}
]);
But following error raises
TypeError: Cannot read property 'nodeName' of undefined
at La (http://localhost:8080/flipxl/scripts/angular.min.js:142:109)
at Object.Kb.$set (http://localhost:8080/flipxl/scripts/angular.min.js:65:380)
at Object.fn (http://localhost:8080/flipxl/scripts/angular.min.js:63:358)
at k.$digest (http://localhost:8080/flipxl/scripts/angular.min.js:109:172)
at k.$apply (http://localhost:8080/flipxl/scripts/angular.min.js:112:173)
at h (http://localhost:8080/flipxl/scripts/angular.min.js:72:454)
at w (http://localhost:8080/flipxl/scripts/angular.min.js:77:347)
at XMLHttpRequest.z.onreadystatechange (http://localhost:8080/flipxl/scripts/angular.min.js:78:420)
Have any solution please share with me
Works perfectly fine for me when adding a $scope.$apply because of the ready event and fixing the missing braces (DEMO, iframes unfortunately don't seem to work in SO snippets).
I was not able to reproduce your error though.
mainApp.controller('DailyReportsController',
['$scope', '$state', '$rootScope', 'mainWebService', '$http', '$sce', function($scope, $rootScope, $http, $sce) {
angular.element(document).ready( function() {
//var drtab = new Royal_Tab($('.dailyrpts_tabs.royal_tab'));
$scope.$apply(function() {
$scope.content = $sce.trustAsResourceUrl("https://gcc.geojit.net/researchdesk/OPTION STRATEGIES2.pdf");
});
});
}]);
You can use directive feature for this as below.
var ngApp = angular.module("ngApp",[]);
ngApp.directive("pdfLoader",function(){
return function(scope,elem,attr){
elem.append("<object width='100%' height='100%' src='"+ scope.content +"' type='application/pdf'></object>");
};
});
ngApp.controller("ngCtrl",function($scope){
$scope.content ="https://gcc.geojit.net/researchdesk/OPTION STRATEGIES2.pdf";
});
and html like below
<div style="height:100%" pdf-loader></div>
Take a look at running example for this at http://jsbin.com/quzoyiloke , And code at http://jsbin.com/quzoyiloke/3/edit?html,js
You can also try by creating new html file whose content is as following.
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp',[]);
myApp.directive("pdfLoader",function(){
return function(scope,elem,attr){
elem.append("<object width='100%' height='100%' src='"+ scope.content +"' type='application/pdf'></object>");
};
});
myApp.controller("ngCtrl",function($scope){
$scope.content ="https://gcc.geojit.net/researchdesk/OPTION STRATEGIES2.pdf";
});
</script>
</head>
<body ng-app="ngCtrl">
<div ng-controller="ngCtrl">
<div style="height:100%" pdf-loader></div>
</div>
</body>
</html>
I have the following HTML:
<!doctype html>
<html lang="en" ng-class="theme">
<head>
...
</head>
<body>
<form>
<button class="white-gradient glossy" ng-click="theme = 'darkBlue'">Blue</button>
<button class="white-gradient glossy" ng-click="theme = 'black'">Black</button>
</form>
#Scripts.Render("~/bundles/Angular")
<script type="text/javascript">
angular.element(document).ready(function () {
angular.bootstrap(angular.element(document).find('html'), ['app']);
});
</script>
</body>
</html>
The buttons act as theme switchers to change my CSS and this works fine.
Here's my app.js
var app = angular
.module('app', ['ui.router', 'admin', 'home', 'questions', 'ngResource', 'LocalStorageModule'])
.config(['$locationProvider', '$sceProvider', '$stateProvider',
function ($locationProvider, $sceProvider, $stateProvider) {
$sceProvider.enabled(false);
$locationProvider.html5Mode(true);
var home = {
name: 'home',
url: '/home',
views: {
'menu': {
templateUrl: '/Content/app/home/partials/menu.html',
},
'content': {
templateUrl: '/Content/app/common/partials/empty.html',
}
}
}
$stateProvider
.state(home));
}])
.run(['$rootScope', '$scope', '$state', '$stateParams', function ($rootScope, $scope, $state, $stateParams) {
$scope.theme = 'darkBlue'
}])
.controller('appController', ['$scope', '$resource', '$state', function ($scope, $resource, $state) {
$scope.state = $state;
}]);
I am trying to set the default theme (line 2 of the HTML) at startup to 'darkBlue'.
However this does not seem to work. When my application starts the theme is not defined.
Can someone tell me what I am doing wrong and why it seems to ignore the line $scope.theme = 'darkBlue' ?
Note I also tried the following and this does not set the theme either:
.run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$state.transitionTo('home')
}])
.controller('appController', ['$scope', '$resource', '$state', function ($scope, $resource, $state) {
$scope.state = $state;
$scope.theme = 'darkBlue'
}]);
In your original example, you're injecting $scope into the run function
.run(['$rootScope', '$scope', '$state', '$stateParams', function ($rootScope, $scope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$state.transitionTo('home')
$scope.theme = 'darkBlue'
}])
but run cannot inject $scope because it isn't run against any particular view or controller. You can, however, inject $rootScope (as you already are) and set the data there:
.run(['$rootScope', '$scope', '$state', '$stateParams', function ($rootScope, $scope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$state.transitionTo('home')
$rootScope.theme = 'darkBlue'
}])
Prototypal inheritance will ensure that theme is available as a property on any child scope; however, you won't be able to change that value, because in JavaScript, writing to a property in this manner overwrites the property on the child object (e.g. setting $scope.theme in a controller would not propogate the change back up to the $rootScope, as you saw in your second example). See this wiki article for more information.
What you would most likely want to do is create a service to serve as the shared state between all the various places you want to access and change the data. You can find more information about services in the Developer Guide and as a video tutorial on egghead.io, but basically you can inject them into any number of controllers and the controllers share a single instance of the service. For example, it may look something like this:
<body>
<div ng-controller="ThemeController">
<form>
<button class="white-gradient glossy"
ng-click="theme.set('darkBlue')">Blue</button>
<button class="white-gradient glossy"
ng-click="theme.set('black')">Black</button>
</form>
</div>
#Scripts.Render("~/bundles/Angular")
#Scripts.Render("~/bundles/AngularApp")
<script type="text/javascript">
angular.element(document).ready(function () {
angular.bootstrap(angular.element(document).find('html'), ['app']);
});
</script>
</body>
Then, you can set up your service and inject it into controllers:
var app = angular
.factory('theme', function() {
var theme = null;
// every time you inject `theme`, it will inject the same instance
// of this object, which contains methods for getting and setting
// the current theme
return {
get: function() { return theme; },
set: function(t) { theme = t; }
};
})
// we can set the default theme in a `run` function
// by injecting it
.run(function(theme) {
theme.set('darkBlue');
})
// Here is the new `ThemeController` we created in the template, above
.controller('ThemeController', function($scope, theme) {
// bind `theme` to the scope so we can change it
$scope.theme = theme;
})
.config( // rest of app config
Working example: http://jsfiddle.net/BinaryMuse/bnAzp/