Angularjs. Open content in new tab - angularjs

I've read similar questions/answers on SO, but can't resolve my problem.
Here is the setup:
index.html
<li ng-repeat="a in article">
<a ng-click="articleDetails(a.id)">
{{a.title_en}}
</a>
</li>
js file
angular.module('myApp.article', ['ngRoute'])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/article/:id', {
templateUrl: 'article/article.html',
controller: 'ArticleDetailCtrl'
});
//$locationProvider.html5Mode(true);
}])
.controller('ArticleDetailCtrl', ['$http', '$routeParams', '$scope', '$window', '$location',
function ($http, $routeParams, $scope, $window, $location) {
$scope.params = 'blabla';
}])
article.html
<div>{{params}}</div>
Question: When I click the link in index.html new tab is opened as expected with correct url, however, instead of article details I get Not found on the webpage. What might be a problem?
EDIT 1: Function articleDetail is defined as follows in another controller that is used in index.html:
$scope.articleDetails = function (id) {
$scope.id = id;
$scope.window = $window.open('article/' + id, '_blank');
}

You cannot retain the scope of your Angular application in another window. Hence calling $window.open will open a new window which does not have your original $scope.
The scope is tied only to the window in which the ngApp is initialized.
In order to overcome this, you can use the LocalStorage of your browser.
EDIT: Please refer this

Related

AngularJS Controller not registered

I'm new using Angular with MVC Web Api but using VB instead of C#. I'm trying to make an SPA web site and I have some week trying to solve this problem.
In my app.js I defined the routing to my views and the controllers I'm going to use in them
var goMessage = angular.module('goMessage', ['ngRoute', 'goMessage.controllers', 'goMessage.services', 'goMessage.directives']);
angular.module('goMessage.controllers', []);
angular.module('goMessage.services', []);
angular.module('goMessage.directives', []);
goMessage.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
//Vista Login
$routeProvider.when('/login/inicio', {
controller: 'loginController',
controllerAs: 'lgCtrl',
templateUrl: 'Home/Login'
});
//Vista Usuarios
$routeProvider.when('/usuarios/lista', {
controller: 'usuariosController',
controllerAs: 'usCtrl',
templateUrl: 'Home/Usuarios'
});
$routeProvider.when('/dashboard/inicio', {
controller: 'dashboardController',
controllerAs: 'dashCtrl',
templateUrl: 'Home/Dashboard'
});
$locationProvider.html5Mode(true);
}]);
The usuariosController.js controller is working very well, its code is:
angular.module('goMessage.controllers')
.controller("usuariosController", ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
//Ordenamiento por default
this.ordenarPorColumna = 'UsuarioID';
this.reverse = false;
// More code...
}
]);
And the loginController.js controller code is:
angular.module('goMessage.controllers')
.controller('loginController', ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
this.myData = "Data$$$";
}
]);
In the Login.vbhtml view I'm following the same pattern as the Usuarios.vbhtml view. I define my ng-app in the _layout.vbhtml and I don't define any controller inside any view.
The error I'm unable to solve is this:
Error Image
Look at the AngularJs Expression
As you can see, I've defined both controller using the same way but the only one that works is the usuarios one and any other controller I add doesn't work.
Here I show you the scripts loading order:
Scripts Loading Order
I'm using my local IIS and working in VS2012.
The angular JS version is 1.6.
To register the logic modules as controller, filter and etc..., you need to add this code in your app.config
var app = angular.module("App", []);
var config = function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.register;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
//your codes
}
config.$inject = ["$controllerProvider", "$compileProvider", "$filterProvider", "$provide"];
app.config(config);
Why this happen?
sometimes we don't need to add all of controllers in our main index which has ng-view or ui-view for that we should put our controller as lazyload to the app.config as you do this in your config, because of that the main app for get the controllers need to register controllers and other modules.
This issue might happen due to asynchronous loading of scripts. The script order might also be an issue. You can add a console.log at the beginning of loginController to check whether the component is loaded correctly.

AngularJs multiple Controllers, ng-click and ng-view

This might be me just missing something or getting the wrong end of the stick on the tutorial, so bear with me.
I have my app....
var shepApp = angular.module('shepApp', [
'ngRoute',
'ui-notification',
'shepControllers',
'shepFilters',
'shepServices'
]);
shepApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/galaxies', {
templateUrl: "partials/galaxies.html",
controller: 'GalaxyListCtrl'
}).
}]);
And my controllers go something like this....
var shepControllers = angular.module('shepControllers', []);
shepControllers.controller('GalaxyListCtrl', ['$scope', '$location', 'Notification', 'Galaxy', function($scope, $location, Notification, Galaxy) {
$scope.galaxys = Galaxy.query();
$scope.blah = function(){
alert(123);
}
}]);
shepControllers.controller('GalaxyDetailCtrl', ['$scope', '$routeParams', '$location', 'Notification', 'Galaxy', function($scope, $routeParams, $location, Notification, Galaxy) {
$scope.galaxy = Galaxy.get({slug: $routeParams.slug});
}]);
My galaxies.html partial contains the following HTML using ng-click.
<button ng-click="blah"></button>
My thinking was that that blah function for the click event would be exposed when my route is /galaxies and the controller in use is GalaxyListCtrl - but the alert is never fired at all.
I think I am missing something in the way this all fits together.
Calling a function without arguments is done using the name of the function followed by parentheses:
ng-click="blah()"

Close window from within a view in AngularJS

I'm trying to close a window from within a view in AnglarJS but I'm getting this error:
Scripts may close only the windows that were opened by it.
This is the script in index.html:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {templateUrl: 'main.html', controller: 'mainCtrl'})
.otherwise({redirectTo: '/'});
});
app.controller('mainCtrl', function($scope, $route, $routeParams, $location, $window) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
$scope.closeApp = function(){
$window.close();
};
});
and this is main.html:
<button ng-click="closeApp()">Close this app please</button>
I'm aware that from the latest working spec for window.close():
The close() method on Window objects should, if all the following conditions are met, close the browsing context A:
The corresponding browsing context A is script-closable.
The browsing context of the incumbent script is familiar with the browsing context A.
The browsing context of the incumbent script is allowed to navigate the browsing context A.
But how come that I'm getting this? Am I not within the same context?! And how to fix that?
Thanks.

cannot access $scope variables in controller - AngularJS

I created an Angular app that uses Bootstrap. I based the project on a template that I downloaded and studied. I downloaded it from here: https://angularstart.codeplex.com
I did not use or modify the template to create the project that I have now. Instead, I created a new project and used Nuget to download the latest packages for Angular & Bootstrap.
The problem is in my 'Contact' page, which has a form for site visitors to send me a message. I have defined a function - sendMessage - inside the controller which is bound by ng-click to a button in the HTML.
appRoot.controller('ContactController', ['$scope', '$http', function ($scope, $http) {
$scope.contactModel = {};
$scope.sendMessage = function () {
alert('msg: ' + $scope.contactModel.msgSubject);
}
}]);
<input type="text" id="msgSubject" name="msgSubject" data-ng-model="contactModel.msgSubject" />
<button class="btn btn-primary" ng-click="sendMessage()" >Send Message</button>
The button and click event works fine but inside the function, it cant access the model variable. It returns with an 'undefined' - the alert says "msg: undefined"
I've researched this for three days now. I've looked at other demo code on plunkr and jsfiddle and I've seen it work but something in my setup prevents access to the scope variables (basically my defined model vars).
My angular app.js is:
var appRoot = angular.module('main', ['ngRoute', 'ngResource']);
appRoot
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', { templateUrl: '/main/home', controller: 'HomeController' })
.when('/home', { templateUrl: '/main/home', controller: 'HomeController' })
.when('/contact', { templateUrl: '/main/contact', controller: 'ContactController' })
}])
.controller('RootController', ['$scope', '$route', '$routeParams', '$location', function ($scope, $route, $routeParams, $location) {
$scope.$on('$routeChangeSuccess', function (e, current, previous) {
$scope.activeViewPath = $location.path();
});
}]);
I've tested adding the variable when initializing the contactModel variable:
$scope.contactModel = { msgSubject: 'tst sub' };
The alert inside the 'sendMessage' function sees this and shows "msg: tst sub" correctly.
I've tried different configurations for the ContactController, including passing $location and $resource like so:
appRoot.controller('ContactController', function ($scope, $location, $resource) {
}
but still can't access the scope variables.
In all the samples & demos I've checked out - including the Angular Start tempate - the controller can access the defined ng-model variable. Makes me think it has to be in my configuration or use of the differnt versions of either Angular or Bootstrap.
My _Layout.cshtml defines the default controller and ng-app as so:
<body data-ng-app="main" data-ng-controller="RootController"style="background-color:transparent;" >
Angular version is v1.2.2 and Bootstrap is v3.1.0
Any help is apporeciated. Thanks
I think I've narrowed it down. I'd like to add that I am also using ASP.NET MVC with Razor.
If I put the HTML code outside the #RenderBody() and I put the javascript alert inside the RootController, the code works:
<div >
<div>
<input type="text" id="msgSubject" name="msgSubject" data-ng-model="contactModel.msgSubject" />
<button class="btn btn-primary" ng-click="sendMessage()" >Send Message</button>
</div>
</div>
<div >
#RenderBody()
</div>
And the Javascript:
app.controller('RootController', ['$scope', '$route', '$routeParams', '$location', function ($scope, $route, $routeParams, $location) {
$scope.$on('$routeChangeSuccess', function (e, current, previous) {
$scope.activeViewPath = $location.path();
});
$scope.contactModel = {};
$scope.sendMessage = function () {
alert('msg: ' + $scope.contactModel.msgSubject);
}
}]);
If the HTML is inside the partial view (cshtml), the Angular controller does not see the scope variable as defined by ng-model.
Perhaps Angular execution is blocked by ASP.NET MVC's Razor engine? Something's going on in the #RenderBody() that is probably stripping the functionality out..

Angular - Return ID from URL Path in Controller

I am building a rather simple AngularJS app, but for simplicity's sake, I'd rather not use the routing (if possible), and just serve back individual Angular pages from the server. Essentially, use Angular only for layout and functionality of 'widgets' and not for moving between pages.
With that said, I've spent hours trying to get an ID out of the current URL, so:
/Tickets/:id
All I want to do in my controller, is get the ID from the URL, then pass that to a Factory. (below is an example using pseudocode)
app.controller('ticketController', ['$scope', '$route',
function ($scope, $route, $location) {
//Get ID out of current URL
var currentId = someFunction().id;
factory.callFactory(ID);
}]);
I've also tried creating routes, but the objects returned don't seem to provide a way to get the ID.
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/tickets/:id',
{
templateUrl: '/partials/edit',
controller: 'ticketController'
}
);
}]);
Not sure what I'm doing wrong.
This doesn't seem to work for me
This also doesn't seem to work, but I may be doing something wrong
Try $routeParams instead:
app.controller('ticketController', ['$scope', '$routeParams',
function ($scope, $routeParams) {
//Get ID out of current URL
var currentId = $routeParams.id;
}]);
If you are using ui-router so try $stateParams:
app.controller('ticketController', ['$scope', '$stateParams',
function ($scope, $stateParams) {
//Get ID out of current URL
var currentId = $stateParams.id;
}]);

Resources