ui router not activating the controller in template context - angularjs

I have a template which would be resolved in ui-view as
<div class="row login" >
<div class="col-xs-12 col-sm-8 col-md-6 " ng-class="offSet">
</div>
</div>
Now The ui router state which resolves this template from templateUrl is
.state('login.register', {
url: "login/register",
views: {
"#": {
templateUrl: "/Account/Register"
},
controller: "loginController"
}
})
And the controller is :
ngApp.controller('loginController', ['$scope', '$state', function ($scope, $state) {
$scope.offSet = "col-lg-offset-3";
$scope.login = function () {
$state.go('dashboard.home');
}
}])
Now what I want is the ng-class should get applied as soon as the template resolves and rendered. But thats not happening . the ng-class is not getting applied if I dont provide ng-controller attribute .
However when I put the ng-controller='loginController' in my template as
<div class="row login" ng-controller="loginController">
<div class="col-xs-12 col-sm-8 col-md-6 " ng-class="offSet">
</div>
</div>
Then the class gets attached and I can see the effect on resulting dom.
But as far as ui router documentation says . the controlller gets attached to the dom as soon as the template is resolved .
Any idea why without ng-controller attribute its not working ????

You are almost there, solution here is surprisingly simple. Controller belongs to the view, in our case to "named" view, not to the cluster views:
.state('login.register', {
url: "login/register",
views: {
"#": {
templateUrl: "/Account/Register"
controller: "loginController" // here it will be used
},
//controller: "loginController" // just skipped
}
})
In case we'd like to reuse one controller for more named views, we just repeat its definition for each of them...

Related

Always show 1 view outside of ng-view - angular

I have the following controllers, and I want the template of the CategoryController to be shown on all pages (ie with all other views). the app displays all categories with this controller, when you click a category it shows all books in that category, then when you click a book it shows the books details. I want the categories to be always shown, can this be done ng-include?
app.config(function ($routeProvider) {
$routeProvider
.when('/books', {
controller: 'BookshelfController',
templateUrl: 'views/bookshelf.html'
})
.when('/books/:bookId', {
controller: 'BookController',
templateUrl: 'views/book.html'
})
.when('/categories', {
controller: 'CategoryController',
templateUrl: 'views/categories.html'
})
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
.otherwise({
redirectTo: '/books'
});
});
html
<div class="main">
<div class="container">
<div ng-view></div>
</div>
</div>
As #Hadi says, use angular-ui-router, or why not just place the controller directly over the view when it should be shown on every page, anyway?
<div class="main">
<div class="container">
<div ng-controller="CategoryController"></div>
<div ng-view></div>
</div>
</div>

How to use 1 ui-view if there are multiple ui-view elements with the same name?

I have a html structure like so,
<div class="content-wrapper">
<div class="content">
Click me
</div>
<div ui-view="content-view">Template goes here</div>
</div>
<div class="content-wrapper">
<div class="content">
Click me
</div>
<div ui-view="content-view">Template goes here</div>
</div>
Two content-wrapper divs with both a ui-view called content-view.
And my state config looks like this,
$stateProvider
.state('home', {
url: ''
})
$stateProvider
.state('content-view', {
url: '',
views: {
"content-view": {
template: '<div>Content</div>',
}
},
})
See it in action here > http://plnkr.co/edit/997KbH9beLLHClM0IKb9?p=preview
If a user clicks on one of two ui-sref elements both the ui-view 'content-view` elements get triggered and inject the template.
What I would like to see is that only the ui-view in the content-wrapper element that gets clicked gets triggered.
Hiding one or the other element wouldn't be a good solution, because then the views will still have to load all the data in them. So I think my best bet is to target the specific ui-view in the same content-wrapper element.
* Update *
I've updated my plunker > http://plnkr.co/edit/997KbH9beLLHClM0IKb9?p=preview
I create several rows with content divs in them. Each row has 1 ui-view element. If a user clicks on one of the links it places the template in each view. While I want to target the view that's inside the content wrapper that the user clicked on.
Instead of nested views you can use directive here as you have repeating same objects so nested views do not help you that much...
just define a directive which is only for templating (of course you can extend its feature by your needs)..,
app.directive('contentTemplate', function() {
return {
restrict: 'E',
template: '<div class="content-view">{{vm.movie.title || "No Movie"}} is selected</div>',
scope: {
movie: '='
},
controller: ContentTemplateController,
controllerAs: 'vm',
bindToController: true
}
})
function ContentTemplateController() {
// your directive controller if you need it
}
then bind your selected content with directive then whenever you change movie content of directive will be changed as well...
<div class="content-wrapper" ng-repeat="movieGroup in movieGroups">
<div class="content" ng-repeat="movie in movieGroup">
<button ng-click="movieGroup.selectedMovie = movie;">{{ movie.title }}</button>
</div>
<content-template movie="movieGroup.selectedMovie"></content-template>
</div>
Creating independent ui-view states with the same name is simply not possible with the current model that ui-router has provided. The closest possible implementation is probably ui-router-extras's sticky module. You can create multiple independent(sticky) states by taking advantage of multiple named views in a state.
DEMO
Javascript
app = angular.module('myApp', [
'ui.router',
'ct.ui.router.extras'
]);
app.controller('mainCtrl', ['$scope',
function($scope){}
])
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
url: '/'
})
.state('main.sub1', {
sticky: true,
views: {
'sub1#': {
template: 'sub1<ui-view />'
}
}
})
.state('main.sub1.part1', {
template: '.part1'
})
.state('main.sub2', {
sticky: true,
views: {
'sub2#': {
template: 'sub2<ui-view />'
}
}
})
.state('main.sub2.part1', {
template: '.part1'
});
});
HTML
<div class="content-wrapper">
<div class="content">
<a ui-sref="main.sub1">main.sub1</a> |
<a ui-sref="main.sub1.part1">main.sub1.part1</a>
</div>
<div ui-view="sub1">Template goes here</div>
</div>
<div class="content-wrapper">
<div class="content">
<a ui-sref="main.sub2">main.sub2</a> |
<a ui-sref="main.sub2.part1">main.sub2.part1</a>
</div>
<div ui-view="sub2">Template goes here</div>
</div>

Angular ng-bind disappearing using escaped fragments with Mean-SEO

I have an angular web app that I am trying to get escaped_fragments to work using Mean-seo (under the covers it uses phantomjs headless browser)
I am getting strange behaviour I can't explain.
The non escaped fragment works fine.
With escaped fragments some of the content immediately disappears.
I have an object that I am reading from the mongo db in the resolve section of the routes config like so.
state('view-creator-test', {
url: '/view-creator-test/:creatorId',
templateUrl: 'modules/creators/views/view-creator-test.client.view.html',
resolve: {
creator: function($stateParams, Creators) {
return Creators.get({
creatorId: $stateParams.creatorId
}).$promise;
}
},
controller: function($scope, creator) {
$scope.resolveCreator = creator;
}
}).
then the view template is
<section data-ng-controller="CreatorTestController" >
<!-- !CREATOR PROFILE -->
<section class="profile-header inverse">
<div class="container">
<!-- AVATAR -->
<div class="row">
<!-- NAME / LOCATION -->
<div class="col-sm-8 col-sm-offset-1 col-xs-12 text-center-sm">
<div class="row">
<div class="col-sm-6 col-xs-12">
<h2 class="name">{{creator.name}}</h2>
<h2 class="name" ng-bind="creator.name"></h2>
</div>
<h2 class="name">{{test}}</h2>
<h2 class="name" ng-bind="test"></h2>
</div>
</div>
</div>
</div>
</section>
</section>
then the controller is
'use strict';
angular.module('creators').controller('CreatorTestController', ['$scope',
function($scope) {
$scope.test = 'Leo was Here';
$scope.creator = $scope.resolveCreator;
}]);
the result is that the creator name is filled in for {{creator.name}} but is not filled in for ng-bind="creator.name".
'Leo was here' is filled in for both.
Thanks
Instead of defining controller function in state and then do assign that $scope inside variable through template, you could place the CreatorTestController inside the route, so that you directly inject the dependency inside the CreatorTestController function, Remove ng-controller from the template
.state('view-creator-test', {
url: '/view-creator-test/:creatorId',
templateUrl: 'modules/creators/views/view-creator-test.client.view.html',
resolve: {
creator: function($stateParams, Creators) {
return Creators.get({
creatorId: $stateParams.creatorId
}).$promise;
}
},
controller: 'CreatorTestController'
})
Controller
'use strict';
angular.module('creators').controller('CreatorTestController', ['$scope', 'creator', //<-- injected resolve method here.
function($scope, creator) {
$scope.test = 'Leo was Here';
$scope.creator = creator;
}]);

ui-router rendering ui-views in view templates

Just checking an approach for ui-router. Was sure it could do this but hitting some friction. I want my third template to render inside my 2nd template - but my controller is not even initialized for my 3rd state unless I define my ui-view in my 1st template.
Example code
Template 1 This is rendered from an MVC view
<div class ="animate-container" ng-app="uiRouter-Browse">
<div class="products-slide-animate" ui-view="cat1">
<div>
<div><a ui-sref="cat1({id:1})">1</a></div>
<div><a ui-sref="cat1({id:2})">2</a></div>
<div><a ui-sref="cat1({id:3})">3</a><div>
</div>
</div>
</div>
Template 2
<div>
<div class="row all-categories-wrapper">
<div class="col-xs-12 list-item">
<a href="#/" class="parent">
<i class="chevron-left"></i>
<div>All Categories </div>
</a>
</div>
</div>
</div>
<!--want 3rd template to render here -->
<div ui-view="cat2" class="products-slide-animate" autoscroll="false">
<div class="cat2-wrapper" ng-repeat="cat1 in data.Cat1s">
<div class="row">
<div class="col-xs-12 list-item">
<a ui-sref="cat2({id:{{cat1.ID}}, name:'{{cat1.UrlEncodedName}}'})">
<div class="list-item-text">{{cat1.Name}}</div>
<i class="chevron-right"></i>
</a>
</div>
</div>
</div>
</div>
Template 3
<div>
//some content to render
</div>
My ui-router script
var browse = angular.module('uiRouter-Browse', ['ui.router', 'ngAnimate'])
.run(
['$rootScope', '$state', '$stateParams',
$rootScope.$on('$stateChangeSuccess',
function (event, toState, toParams, fromState, fromParams) {
console.log(toState.name);
console.log(fromState.name);
}
);
}]);
browse.config(
['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise('/');
$stateProvider
.state('cat1', {
url: '/cat1/:id?name',
views: {
'cat1': {
templateUrl: '/Template1.html',
controller: //Get some data and return
}
}})
.state('cat2', {
url: '/cat2/:id?name',
views: {
'cat2': {
templateUrl: '/Template2.html',
controller: //Get some data and return
}
}
});
}]);
Most if not all of the examples I see the entire ui-view is replaced, as opposed to partially being replaced - i.e. the rendering of template 3 in the ui-view in template 2.
So when click on the cat 1 links from template 1, it transitions to the next state, the controller is invoked and my animations are pretty.
When I click on a cat2 link, my state is invoked correctly but the controller is not fired. I then just animate back to my previous view/state.
If I place a ui-view="cat2" div in template 1 then the controller fires and my template renders. I just would like it to render within the ui-view in template2.
Thanks
While not sure if it will really suite to your needs, the reason and solution is in a different state definition, we need state nesting. We simply cannot have two "totally" independent states, and try to inject one into another. We have to make one of them Parent and one to be a Child:
Current scenario:
$stateProvider
.state('cat1', {
...
}})
.state('cat2', {
...
});
Both states are in this snippet on the same "root" level. If we would like to nest the cat2 into cat1 they must be defined like this:
$stateProvider
.state('cat1', {
... // this is a parent
}})
.state('cat1.cat2', {
... // this is a child
});
That will lead to url for a (sub)state cat2 to be built from both parent and its own:
#/'/cat1/:id/cat2/:id?name&nameurl',
but if we do not need Parent url part and its parameters we can use absolute url:
.state('cat2', {
url: '^/cat2/:id?name',
See:
Methods for Nesting States
Absolute Routes (^)

nest ng-view inside a form

given the controller
function ctl($scope, $http) {
$scope.postForm = function() {
console.log("submitting form")
}
}
and the view
<form name="pform" ng-show="!error.Show">
<div ng-view></div>
<button type='button' value='Save' ng-click="postForm()" />
</form>
The controller method postForm doesn't get called, however, if i move the form tag into the view the method is called. Is there a reason that this doesn't work as I expect it to? Is there another way to accomplish the goal of sharing the form controls across different views?
Update
my module and routeProvider are configured like this:
angular.module("profilemodule", [])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/info", { templateUrl: '/partials/profile/info.html', controller: ProfileController })
.when("/user", { templateUrl: '/partials/profile/user.html', controller: ProfileController })
.when("/introduction", { templateUrl: '/partials/profile/editor.html', controller: ProfileController })
.otherwise({ redirectTo: '/info' });
}]).run(function ($rootScope, $location) {
$rootScope.location = $location;
})
and the page includes some nav elements which are set based on the location service like so:
<div class="row">
<div class="offset2 span10">
<ul class="nav nav-pills">
<li ng-class="{active: location.$$path.substring(0, '/info'.length) == '/info'}"><a href="#/info" >Information</a></li>
<li ng-class="{active: location.$$path.substring(0, '/user'.length) == '/user'}"><a href="#/user" >User</a></li>
<li ng-class="{active: location.$$path.substring(0, '/intro'.length) == '/intro'}"><a href="#/intro" >Introduction</a></li>
</ul>
</div>
</div>
<form name="pform" method="POST" ng-show="!error.Show">
<div ng-view></div>
<button type='button' value='Save' ng-click="postForm()" />
</form>
the ng-class statements works perfectly, is it because I've set the location property of $scope in the module's run method?
thanks,
jason
ng-view with routing creates a new scope with the controller, and you can't reach a child scope. Your submit action lies in the parent scope and the form data lies in the child scope (created by ng-view).
If you want to use common form controls, you can use ng-include, this directive gets template it and renders that in the current scope.
Move your form controls to a new template, then include them in all of your forms.
API reference:
http://docs.angularjs.org/api/ng.directive:ngInclude

Resources