I am using UI-Router and trying to access my web app's current state from within a directive, using the following:
footer.directive.js
(function () {
'use strict';
angular
.module('app')
.directive('myFooter', myFooter);
myFooter.$inject = ['$cookies', 'userFactory', '$state', '$log', '$rootScope'];
function myFooter($cookies, userFactory, $state, $log, $rootScope) {
var directive = {
restrict: 'E',
templateUrl: 'app/components/footer/footer.html',
controller: FooterController,
controllerAs: 'vm',
bindToController: true
};
return directive;
function FooterController($state) {
var vm = this;
vm.currentState = $state;
}
}
})();
footer.html
<div class="footer">
<p>{{ vm.currentState.current.name }}</p>
</div>
When I run $log.log($state) it posts an object in my console that has a current object with a name attribute that is equal to the state name that I need, but when I try to reference the $state.current.name, either on my view or by logging it to the console, it displays as an empty string.
I'm a bit new to Angular, so if someone could explain to me what is going on here or at the least how to fix this so that I can display what I want properly, that would be a huge help. Thanks!
Edit: Two other questions that I looked at before posting this one are:
This one which seems to deal more with changing a class name based on state name, and this one, which doesn't quite address my problem either (and doesn't look like it could possibly be the right way to do this.)
First of all, there is a naming bug in your posted code! (amaiFooter)
The second thing is, if you log an object, it's bound by a call by reference
So the moment you log it, you log the reference. That means when you look at it, it can contain other values than when you have logged it
But when you logged the state name and it was undefined, that was the right output!
You can try to wrap it in a $timeout function with 0 delay, just to add your code to the end of the current digest cycle, that should solve your problem
You need inject the state service on the controller as follows
(function () {
'use strict';
angular
.module('app')
.directive('myFooter', myFooter);
myFooter.$inject = ['$cookies', 'userFactory', '$state', '$log', '$rootScope'];
function myFooter($cookies, userFactory, $state, $log, $rootScope) {
var directive = {
restrict: 'E',
templateUrl: 'app/components/footer/footer.html',
controller: FooterController,
controllerAs: 'vm',
bindToController: true
};
return directive;
}
FooterController.$inject = ['$state'];
function FooterController($state) {
var vm = this;
vm.currentState = $state;
}
})();
Related
how i can use something like resolve in config in directives?
I have such code:
angular.module('config', ['ngRoute', 'resources.params'])
.config(['$routeProvider', function($routeProvider) {
'use strict';
$routeProvider
.when('/config',{
templateUrl: 'templates/config/config.tpl.html',
controller: 'ConfigCtrl',
resolve: {
params: ['Params', '$route',
function(Params, $route) {
if ($route.current.params.skey)
return Params.get($route.current.params.skey);
else
return null;
}
]
},
reloadOnSearch: true
});
}
])
.controller('ConfigCtrl', ['$scope','$route','$routeParams', 'params','Params',
function($scope,$route,$routeParams,params,Params){
'use strict';
I can use "params" in my controller because i wrote "params: [..." in my .config
But now i want to use this "params" in my directive:
.directive('mapsysitem', ['$location', '$routeParams', '$freshmark',
function($location, $routeParams, $freshmark) {
'use strict';
return {
restrict: 'E',
require: '^mapsyslist',
scope: {
zoomlist: '#',
item: '=',
skey: '=',
select: '&'
},
replace: true,
templateUrl: 'templates/map/mapsysitem.tpl.html',
controller: ['$element', '$scope', 'System','$filter','Params',
function($element, $scope, System, $filter, Params) {
.....
}]
};
}]);
If i will add "params" to controller options i will have "Unknown provider: paramsProvider <- params". How i can solve this problem? Thaks you.
Due to your use of an isolated scope within your directive, you will need pass the parameter as an attribute in the directive node
Set the scope in the app controller
.controller('ConfigCtrl', ['$scope','$route','$routeParams','params','Params',
function($scope,$route,$routeParams,params,Params){
$scope.myParams=Params
then pass the $scope.myParams to the directive
<mapsysitem param='myParams'></mapsysitem>
Then create the two way binding in your scope
scope: {
param:'='
},
Then you will be able to use this in the directive controller
controller: ['$element', '$scope', 'System','$filter',
function($element, $scope, System, $filter ) {
var myParams= scope.param
I don't think you can get the scope or attributes values of your directive's controller so if you can't you have to use a service (or $rootScope maybe) to share those values (and watch for changes).
Otherwise you may use the link function. You can access to the scope and attributes here. Here is a quote from angular site about controller/link function :
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.
This mean "use link function unless you're really sure you need controller".
See https://docs.angularjs.org/guide/directive
In my Angular app
var mainApp = angular.module('mainApp', ['ngCookies']);
I've defined authCtrl controller:
mainApp.controller('authCtrl', ['$scope, $cookies',function ($scope, $http, $cookies) {
$scope.credentials = {};
$scope.signCheck = function () {
a = $cookies.getObject('session_credentials');
console.log(a);
};
}]);
If I'm removing $scope declaration from array (injection array?)
mainApp.controller('authCtrl', ['$cookies',function ($scope, $http, $cookies) {
$scope becomes undefined.
If I'm removing $cookies — $cookies becomes undefined.
If I keep them both — $injector unknown provider error.
What I'm doing wrong?
Just be sure that you indicate the services in a correct order in the injector array and the controller function params:
Angular docs says:
This is the preferred way to annotate application components. This is
how the examples in the documentation are written.
For example:
someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
// ...
}]);
Here we pass an array whose elements consist of a list of strings (the
names of the dependencies) followed by the function itself.
When using this type of annotation, take care to keep the annotation
array in sync with the parameters in the function declaration.
Perhaps this controller definition will work for you:
mainApp.controller('authCtrl', ['$scope', '$http', '$cookies', function ($scope, $http, $cookies) {
$scope.credentials = {};
$scope.signCheck = function () {
a = $cookies.getObject('session_credentials');
console.log(a);
};
}]);
I'm new to angular and I can't figure out why this isn't working.
When I call {{$state.current.name}} in my view it works perfectly fine, but as soon as I try to pass it to my controller, the state gets "lost".
Here is my setup:
Module:
angular.module('app', ['ui.router'])
.run(function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
})
//followed by boilerplate ui router setup
View:
<home-nav-bar></home-nav-bar>
Directive:
angular.module('app')
.directive('homeNavBar', function () {
return {
restrict: 'E',
templateUrl: 'homeNavBarView.html',
controller: 'navCtrl'
};
})
})();
Controller:
angular.module('app')
.controller('navCtrl', function ($state, $scope) {
alert($state.current.name); //returns empty
});
})();
At this point I am clueless as to why I can get the state name in the view but not in my controller..
Well, ui-router docs say you can access current state's config object using the current property of $state, so there is absolutely no need to attach anything to $rootScope. I have just tested something along the lines of (simplified a bit for readability):
angular.module('myApp')
.controller('SomeCtrl', function ($scope, $state) {
console.log($state.current);
});
The result in Chrome console is:
Object {url: "/some", templateUrl: "app/some.html", controller: "SomeCtrl", name: "some"}
So as you can see all information should be available along with the name.
I am looking to specify the controller that a directive should use via an attribute on the element - i.e. dynamically:
HTML
<div data-mydirective data-ctrl="DynController"></div>
Angular
angular.module('app', [])
.controller('MainController', [function() { ... }])
.controller('DynController', [function() { ... }])
.directive('mydirective', [function() {
return {
controller: 'DynController', // <- make this dynamic
...
}
}]);
You can do the following:
.directive('mydirective', [function() {
return {
controller: function($scope, $element, $attrs){
//Make decision based on attributes or $scope members
if($scope.$attrs.caseA == 'true'){
return new ControllerA($scope, $element, $attrs);
} else {
return new ControllerDefault($scope, $element, $attrs);
}
},
...
}
}]);
Taking it a step farther, you can use $controller
.directive('mydirective', ['$controller',function($controller) {
return {
controller: function($scope, $element, $attrs){
return $controller($attrs.dynamicCtrlName, {$scope: $scope,$element:$element,$attrs:$attrs});
},
...
}
}
In both cases, make sure you provide all the specific injectable dependencies (particular $scope, $attrs, transclude function etc...) your controllers expect. More details on controller injectables here $compile under the controller section - ideally, outer controller function should receive them all pass as locals.
Nothing in the docs about this, but you can do the following. From my understanding this stuff is used under the hood to make ng-controller work.
.directive('mydirective', [function() {
return {
controller: '#',
name: 'ctrl', // <- attribute that specifies the controller to use
...
}
}]);
I think a better approach is just use scope since scope is already bound to controller, i.e.
put what you want to call on controller scope and simple handle it in directive link
I have a problem with my directive and controller. The variable item in scope is undefined in directive, even though I passed it in html. This is my code:
app.js:
var app = angular.module("app", ["ngRoute"]);
app.config(["$routeProvider", function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "views/main.html",
controller: "MainCtrl"
});
}]);
controller.js:
app.controller("MainCtrl", function($scope) {
$scope.item = "x";
});
directive.js:
app.directive("exampleDirective", function() {
return {
restrict: "A",
scope: {
item: "="
},
templateUrl: "views/item.html"
};
});
index.html:
<div ng-view></div>
main.html:
<div example-directive item="item"></div>
item.html:
<div>{{ item }}</div>
UPDATE
I changed my code to:
app.directive("exampleDirective", function() {
return {
restrict: "A",
scope: true,
templateUrl: "views/item.html"
};
});
and now there is "x" in scope.$parent.item. But why it isn't present inside directive?
Although it seems to work just fine with latest Angular stable http://plnkr.co/edit/6oXDIF6P04FXZB335voR?p=preview maybe you are trying to use templateUrl thats pointing to somewhere it doesn't exist.
Another thing, use primitives only when strictly needed. In case you ever need to modify value of item, you won't be able to do so since you are using a primitive. Plus, if you need "more info" to go inside your isolated scopes, and to avoid attribute soup (attr-this="that", attr-that="boop", my-otherstuff="anotheritem.member", etc) you can pass the two-way bind of an object that handle more data.
Or if you need to share state through multiple controllers, directives, etc, use a service instead and use dependency injection, and there's no need to pass in objects/primitives to your isolated scope, and you can assure state, and that's best practice "the Angular way".
This fiddle works: http://jsfiddle.net/HB7LU/2844/ which is essentially the same thing just without the route information.
var myApp = angular.module('myApp',[]);
myApp.directive("exampleDirective", function() {
return {
restrict: "A",
scope: {
item: "="
},
template: "<div>{{ item }}</div>"
};
});
function MyCtrl($scope) {
$scope.item = 'Superhero';
}
With the view:
<div ng-controller="MyCtrl">
<div example-directive item="item"></div>
</div>
This leads me to believe it could be a scope issue. So try encapsulating the controller scope variable in a container:
$scope.cont = { item: 'x' };
And in the view
<div example-directive item="cont.item"></div>