I'm using the Angular UI Pagination angular-ui.github.io/bootstrap/
In this is a useful number I need to access: totalItems
.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
return {
restrict: 'EA',
scope: {
page: '=',
totalItems: '=',
onSelectPage:' &'
},
controller: 'PaginationController',
templateUrl: 'template/pagination/pagination.html',
replace: true,
link: function(scope, element, attrs, paginationCtrl) {
How can I access this from my controller? I have tried $scope.totalItems but nothing happens. No errors.
If I watch totalItems within the directive, it returns the correct value, but like I've said, I need to access it from the controller. Possibly also within the HTML itself.
Thanks
Related
I have this code:
.directive('hostelGridBed', function($rootScope){
return {
restrict: 'E',
scope: {
config: '=',
range: '=',
days: '='
},
link: function(scope, element){
},
controller: ['$scope', function($scope){
$scope.innerStay = '';
function switchStay(data){
$rootScope.$broadcast('SwitchStay', {data: data.config});
};
$scope.onDropComplete = function(data,evt){
//$rootScope.$broadcast
switchStay(data);
console.log('Drop completo bed!');
}
}],
templateUrl: './js/templates/hostelgridbed.html'
}
})
.directive('hostelGridDay', function(StaysFactory){
return {
restrict: 'E',
scope: {
config: '=',
date: '='
},
link: function(scope,element){
},
controller: ['$scope','$rootScope', function($scope,$rootScope){
$scope.switchStay = function(evt, data){
console.log(data);
// Here. How can I access this controller's $scope
}
$scope.$on('SwitchStay', $scope.switchStay);
}],
templateUrl: './js/templates/hostelgridday.html'
}
})
I get data from $broadcast ok, it's all good. Except that I need to access the directive's $scope from within $scope.switchStay function.
Is there a way to accomplish that?
Actually when you $broadcast or $emit the event from the directive, you could send also the directive's scope as parameter. It should work, but this is actually awful and a really bad practice.
What you have to do in these cases is to add a callback parameter to the directive (&) and provide the switchStay function as callback, and simply trigger it from the directive, passing the parameters that you need to access inside the function.
I hope it makes sense.
I have following directive structure.
<test-widget-body>
<test-task-list-filter>
</test-task-list-filter>
<test-task-list>
<test-datatable config="dtConfig" columns="dtColumns" api="dtApi"></test-datatable>
</test-task-list>
</test-widget-body>
Here are respective directives:
test-datatable
angular.module('testDatatable').directive('testDatatable', function () {
var directive = {
controller: 'testDatatableController',
restrict: 'E',
replace: true,
scope: {
config: '=',
columns: '=',
api: '=',
},
link: lnkFunction,
template: '<table class="table"></table>',
};
return directive;
}
testTaskList
angular.module('testTask').directive('testTaskList', function () {
return {
transclude: true,
restrict: 'E',
controller: 'testListController',
controllerAs: 'vm',
templateUrl: '/app/test/directives/test-list/test-list.html',
link: {
pre: preLink
}
};
function preLink(){
var dtColumns = [{
----
}];
var dtConfig =[];
var dtApi =[];
}
}
testTaskListFilter
angular.module('testTask').directive('testTaskListFilter', function () {
return {
restrict: 'E',
controller: 'testListFilterController',
templateUrl: '/app/test/directives/test-list/test-list-filter.html'
};
});
testWidgetBody
angular.module('testWidgetGrid').directive('testWidgetBody', function () {
return {
templateUrl: 'test.html',
link: function ($scope, element) {
}
}
Here I'm able to access dtConfig dtColumns dtApi objects inside testListFilterController controller.
How is this possible as <test-task-list-filter> and <test-task-list> are siblings.
Can anyone explain what is happening in this scenario.
Note: I'm able to access that object when I perform some click action not while directive rendering.
If you look at the declarations for testTaskListFilter directive and the testTaskList directive, neither of them have isolate scopes. You can declare isolate scopes by doing one of the following in the directive: scope: true or scope: {} (like in your testDatatable) directive.
Thus, any directive that does not declare its own scope inherits its parent's. So, testTaskListFilter and testTaskList are both using the same scope. This means that you're then able to
access dtConfig dtColumns dtApi objects inside testListFilterController controller
Here's the Angular wiki post for understanding scopes and scope inheritance
I'm using directive to display html snippets.
And templateUrl inside the directive,
to be able to include snippets as html file.
The directive does not work, if I try to call
inside a builtin ng-repeat directive
({{snip}} is passed as is, without substitute):
div ng-repeat="snip in ['snippet1.html','snippet2.html']">
<my-template snippet="{{snip}}"></my-template>
</div>
For reference, here is the directive:
app.directive("myTemplate", function() {
return {
restrict: 'EA',
replace: true,
scope: { snippet: '#'},
templateUrl: function(elem, attrs) {
console.log('We try to load the following snippet:' + attrs.snippet);
return attrs.snippet;
}
};
});
And also a plunker demo.
Any pointer is much appreciated.
(the directive is more complicated in my code,
I tried to get a minimal example, where the issue is reproducible.)
attrs param for templateUrl is not interpolated during directive execution. You may use the following way to achieve this
app.directive("myTemplate", function() {
return {
restrict: 'EA',
replace: false,
scope: { snippet: '#'},
template: '<div ng-include="snippet"></div>'
};
});
Demo: http://plnkr.co/edit/2ofO6m45Apmq7kbYWJBG?p=preview
Check out this link
http://plnkr.co/edit/TBmTXztOnYPYxV4qPyjD?p=preview
app.directive("myTemplate", function() {
return {
restrict: 'EA',
replace: true,
scope: { snippet: '=snippet'},
link: function(scope, elem, attrs) {
console.log('We try to load the following snippet:' + scope.snippet);
},
template: '<div ng-include="snippet"></div>'
};
})
You can use ng-include, watching the attrs. Like this:
app.directive("myTemplate", function() {
return {
restrict: 'E',
replace: true,
link: function(scope, elem, attrs) {
scope.content = attrs.snippet;
attrs.$observe("snippet",function(v){
scope.content = v;
});
},
template: "<div data-ng-include='content'></div>"
};
});
Just made changes in directive structure. Instead of rendering all templates using ng-repeat we will render it using directive itself, for that we will pass entire template array to directive.
HTML
<div ng-init="snippets = ['snippet1.html','snippet2.html']">
<my-template snippets="snippets"></my-template>
</div>
Directive
angular.module('myApp', [])
.controller('test',function(){})
.directive("myTemplate", function ($templateCache, $compile) {
return {
restrict: 'EA',
replace: true,
scope: {
snippets: '='
},
link: function(scope, element, attrs){
angular.forEach(scope.snippets, function(val, index){
//creating new element inside angularjs
element.append($compile($templateCache.get(val))(scope));
});
}
};
});
Working Fiddle
Hope this could help you. Thanks.
it seems you are trying to have different views based on some logic
and you used templateUrl function but Angular interpolation was not working, to fix this issue
don't use templateUrl
so how to do it without using templateUrl
simply like this
app.directive("myTemplate", function() {
return {
link: function(scope, elem, attrs) {
$scope.templateUrl = '/ActivityStream/activity-' + $scope.ativity.type + '.html'
},
template: "<div data-ng-include='templateUrl'></div>"
};
});
hope this is simple and esay to understand
I am working on multiple directive, this is already existing framework so I dont want to disturb the existing components.
This is my HTML
<div title="test" mydirective>
This is my directive, this has templateUrl with it and this template has another directive getting loaded.
.directive('myDirective', function ($filter) {
restrict: 'A',
replace: true,
transclude: true,
scope: {
title: '#'
},
templateUrl: 'partial/partialtemplate.tpl.html'
});
My Partial Template html looks like this
<div newdirective title="{{title}}"></div>
This is my newdirective
.directive('newDirective', function ($filter) {
restrict: 'A',
replace: true,
transclude: true,
scope: {
title: '#'
},
templateUrl: 'partial/newpartialtemplate.tpl.html',
controller: function ($scope, $attrs) {
//here if I try to print my title I still get {{title}}
console.log($attrs.title);
}
});
So what could the issue be, I the second directive being called even before the template data is written or anything wrong?
I would like to access a parent directive's scope, but I can't seem to get the right combination of settings. Is this possible and is it the right approach?
I really want to avoid putting something like SOME_CONST (which would help me make DOM updates through control flow) in MyCtrl
<div ng-controller="MyCtrl">
<parent>
<child></child>
</parent>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.obj = {prop:'foo'};
}
myApp.directive('parent', function() {
return {
scope: true,
transclude: true,
restrict: 'EA',
template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
link: function(scope, elem, attrs) {
scope.SOME_CONST = 'someConst';
}
}
});
myApp.directive('child', function() {
return {
restrict: 'EA',
template: '<h1>I\'m child.... I want to access my parent\'s stuff, but I can\'t. I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent\'s link function? is this even a good idea? {{SOME_CONST}}. I really don\'t want to put everything inside the MyCtrl',
}
});
Please see this fiddle
Thanks
With transclude: true and scope: true, the parent directive creates two new scopes:
Scope 004 is a result of scope: true, and scope 005 is a result of transclude: true. Since the child directive does not create a new scope, it uses transcluded scope 005. As you can see from the diagram there is no path from scope 005 to scope 004 (except via private property $$prevSibling, which goes in the opposite direction of $$nextSibling -- but don't use those.)
#joakimbl's solution is probably best here, although I think it is more common to define an API on the parent directive's controller, rather than defining properties on this:
controller: function($scope) {
$scope.SOME_CONST = 'someConst';
this.getConst = function() {
return $scope.SOME_CONST;
}
}
Then in the child directive:
link:function(scope,element,attrs,parentCtrl){
scope.SOME_CONST = parentCtrl.getConst();
},
This is how the tabs and pane directives work on Angular's home page ("Create Components" example).
Normally the way you access a parent scope variable in a directive is through bi-directional binding (scope:{model:'=model'} - see the angular guide on directives) in the directive configuration), but since you're using transclusion this is not so straight forward. If the child directive will always be a child of the parent directive you can however configure it to require the parent, and then get access to the parent controller in the child link function:
myApp.directive('parent', function() {
return {
scope: true,
transclude: true,
restrict: 'EA',
template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
controller: function($scope) {
$scope.SOME_CONST = 'someConst';
this.SOME_CONST = $scope.SOME_CONST;
}
}
});
myApp.directive('child', function() {
return {
restrict: 'EA',
require:'^parent',
scope:true,
link:function(scope,element,attrs,parentCtrl){
scope.SOME_CONST = parentCtrl.SOME_CONST;
},
template: '<h1>I\'m child.... I want to access my parent\'s stuff, but I can\'t. I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent\'s link function? is this even a good idea? {{SOME_CONST}}. I really don\'t want to put everything inside the MyCtrl',
}
});
See this update: http://jsfiddle.net/uN2uv/
I just had the same problem and finally solved it with the angular manual ;)
In short: you need to use a controller in your parent directive and require that controller in your child directive. This way you are able to get your parent properties.
See https://docs.angularjs.org/guide/directive
Chapter: Creating Directives that Communicate
I changed your fiddle to use a controller, now you can access your constant:
https://jsfiddle.net/bbrqdmt3/1/
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.obj = {prop:'foo'};
}
myApp.directive('parent', function() {
return {
scope: true,
transclude: true,
restrict: 'EA',
template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
controller: function($scope) {
this.getConst= function() {
return 'someConst';
}
},
}
});
myApp.directive('child', function() {
return {
restrict: 'EA',
require : '^parent',
link: function(scope, element, attrs, ctrl) {
scope.value= ctrl.getConst();
},
template: '<h1>I\'m child.... I want to access my parent\'s stuff, but I can\'t. I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent\'s link function? is this even a good idea? {{value}}. I really don\'t want to put everything inside the MyCtrl',
}
});
There's a transclude fn in the arguments of the link fn after the controller.
myApp.directive('parent', function() {
return {
scope: true,
transclude: true,
restrict: 'EA',
template: '<div><h1>I'm a parent header.</h1></div>',
link: function (scope, el, attrs, ctrl, transclude) {
transclude(scope, function (clone, scope) {
element.append(clone); // <-- will transclude it's own scope
});
},
controller: function($scope) {
$scope.parent = {
binding: 'I\'m a parent binding'
};
}
}
});
myApp.directive('child', function() {
return {
restrict: 'EA',
require:'^parent',
scope:true,
link:function(scope,element,attrs,parentCtrl){
},
template: '<div>{{parent.binding}}</div>' // <-- has access to parent's scope
}
});