I have an element directive that looks like this:
app.directive("ngArticle", [function(){
return {
restrict: "E",
replace: true,
templateUrl: "/partials/article.html",
scope: { article: "=article" }
}
}]);
And used like this:
<ng-article data-article="{{object goes here}}"></ng-article>
This works absolutely fine. But now, I want to access part of the object passed through the directive and process it before it renders out. For example, if the object inside data-article looks like this:
{
category: "Going Out",
id: "1234"
}
In the directive, I want to access the category value, replace whitespace with hyphens and change it all to lowercase. Is this possible within the directive?
I don't want to do this in a controller because the directive is used across multiple controllers.
You can access your object before it rendered using link function within directive:
app.directive("ngArticle", [function(){
return {
restrict: "E",
replace: true,
templateUrl: "/partials/article.html",
scope: { article: "=article" },
link(scope, element, attrs) {
...
}
}
}]);
Also, scope is not interpolated before the linking function so you can watch your article object:
scope.$watch('article', function() {
// do your transformations here
}
Remember to clean up your watchers before your directive destroy, this can prevent memory leaks
scope.$on('$destroy', function () {
// clean up watchers here
});
Related
I have 3 directive with isolate scope and share scope and I want pass a function beteween outermost a innermost directive. The outer and middle has isolate scopes and the middle with inner share the scope. Any suggest ?
Pass the functions of my controller as shown below .
<outer on-edit="helloWorld" ng-model="model" ng-repeat="items in items.objects" ></outer>
In my controller:
$scope.helloWorld = function(){
alert('Hello world');
}
My directive:
angular.module('myApp')
.directive('outer', function () {
return {
restrict: 'E',
replace: true,
scope: {
item: "=ngModel",
onEdit: '&'
},
template: '<div><middle on-edit='onEdit'></middle></div>',
controller : function($scope){
$scope.edit = function(){
$scope.onEdit()();
}
}
};
})
.directive('middle', function () {
return {
restrict: 'E',
replace: true,
scope: {
item : '=ngModel',
onEdit : '&'
},
templateUrl: '<div><inner on-edit='onEdit'></inner></div>'
};
})
.directive('inner', function () {
return {
restrict: 'E',
template: '<div><a ng-click='edit()'>Edit</a></div>'
};
})
And this not work, any ideas?
Thanks
This looks a bad design though, but in the middle directive's template you are using inner directive as follows:
<div><inner on-edit='onEdit'></inner></div>
If you look at it, inner directive has no scope, so the attribute on-edit doesn't make sense there.
If you want to use any method that is present in middle directive can be directly used in inner directive because of shared scope. Think of inner directive as a part of html written in some other html file which will be replaced at run time.
So anything you pass to middle directive is implicitly passed to inner.
I'm looking for an answer to this question:
Multi State button like toggle in angularJS
...but using a directive. The main reason being that I'm trying to achieve isolate scope in order to create a reusable button. I have tried:
angular.module('myApp', [])
.directive('buttonToggle', function() {
return {
restrict: 'A',
scope: {
myBtnArr: "="
},
myBtnTxt: ["AND", "OR", "NOT"],
template: '<button>{{ myBtnTxt[myBtnArr] }} </button>'
}
});
With something like this in the HTML:
<div button-toggle my-btn-arr=0></div>
But Angular doesn't seem to like any flavor of this, either showing the button but not the text or throwing the cryptic a.match is not a function error. Thoughts?
You need to modify your directive to include a link function. Then place myBtnTxt on scope in there. Like so:
app.directive('buttonToggle', function() {
return {
restrict: 'A',
scope: {
myBtnArr: "="
},
template: '<button>{{myBtnTxt[myBtnArr]}}</button>',
link: function(scope){
scope.myBtnTxt = ["AND", "OR", "NOT"];
}
};
});
I'm creating a custom directive similar to a list-box. This is my directive definition:
angular.module('Utilities')
.directive('searchList', [
function () {
return {
restrict: 'E',
templateUrl: '/app/scripts/Utilities/search/search.html',
controller: 'SearchCtrl',
scope: {
itemsSource: '=',
itemTemplate: '#',
filterText: '=?',
selectedItem: '=?',
}
};
}
]);
Here's how I want to use it in my view:
<search-list items-source="productsSource"
item-template="{{item.Name}} Selling for: {{item.Price}}"
selected-item="selectedProduct" />
Both productsSource and selectedProduct come from the view's scope (they work fine). I want item-template to be taken straight up as text (there is no item object in the scope used by my view).
Inside SearchCtrl I obtain the items to show in my search-list, and then I want to apply that item-template to each item (through the use of the $compile service).
The problem is that inside SearchCtrl $scope.itemTemplate is equal to Selling for: (the {{}} syntax was resolved, not passed as text)
tl;dr
My search.html template looks like this:
<li ng-repeat="item in itemsDataSource" ng-class-odd="'oddRow'" ng-class-even="'evenRow'">
<div class="searchResultsItem" ng-click="onItemSelected(item)">
<span compile="internalItemTemplate"></span>
</div>
</li>
Since itemTemplate is one-way binding, the SearchCtrl will reassign it to internalItemTemplate.
if (typeof $scope.itemTemplate === 'undefined') {
$scope.internalItemTemplate = '{{item}}';
} else {
$scope.internalItemTemplate = $scope.itemTemplate;
}
The compile directive on the span tag was borrowed from: Angular Docs for $compile
It looks like this:
angular.module('Utilities')
.directive('compile', ['$compile',
function ($compile) {
// directive factory creates a link function
return function (scope, element, attrs) {
scope.$watch(
function (scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function (value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}
]);
If I hard-code $scope.internalItemTemplate in SearchCtrl to be '{{item.Name}} Selling for: {{item.Price}}', than it works.
How do I get my directive to allow the passing of {{}} without trying to resolve it?
Changing the scope type from # to = and then surrounding it in quotes worked.
The directive would look like this:
angular.module('Utilities')
.directive('searchList', [
function () {
return {
restrict: 'E',
templateUrl: '/app/scripts/Utilities/search/search.html',
controller: 'SearchCtrl',
scope: {
itemsSource: '=',
itemTemplate: '=',
filterText: '=?',
selectedItem: '=?',
}
};
}
]);
and the view would look like this:
<search-list items-source="productsSource"
item-template="'{{item.Name}} Selling for: {{item.Price}}'"
selected-item="selectedProduct" />
I am new to angularjs and i am stuck in accessing directive attributes in controller.
Directive
<rating max-stars="5" url="url.json"></rating>
app.directive('rating', [function () {
return {
restrict: 'E',
scope: {
maxStars: '=',
url: '#'
},
link: function (scope, iElement, iAttrs) {
console.log(iAttrs.url); //works
}
controller
app.controller('ratingController', ['$scope', '$attrs' , '$http','$routeParams',function ($scope,$attrs,$http,$routeParams) {
console.log($attrs.url); //shows undefined
}]);
How do i access the url attribute in controller?
If you want to associate a controller with a directive, you can use the Directive Definition Object's controller property (either specifying the controller as a function or specifying the name of the controller (in which case it can be registered anywhere in your module)).
app.directive('rating', [function () {
return {
restrict: 'E',
scope: {
maxStars: '=',
url: '#'
},
controller: 'ratingController'
};
});
// Meanwhile, in some other file
app.controller('ratingController', function ($scope, $element, $attrs) {
// Access $attrs.url
// Better yet, since you have put those values on the scope,
// access them like this: $scope.url
...
});
When using two-way data-binding via =, the corresponding attribute's value should not be a literal (because you can't have two-way data-binding to a literal), but a string specifying the name of a property in the current scope.
Using <rating max-stars="5"... together with scope: {maxStars: '='... is wrong.
You hould either use <rating max-stars="5"... and scope: {maxStars: '#'...
or <rating max-stars="someProp"... and scope: {maxStars: '='... while the enclosing scope has a property named someProp with a numeric value (e.g. $scope.someProp = 5;).
app.directive('myDirective',function(){
return{
controller: function($scope,$attrs){
console.dir($attrs);
}
}
});
That's it. If you want to access the elements attributes on a controller, you have to set up a controller for the directive.
(You could however, use a shared service to make those attributes available to another controller, if that's want you want to achieve)
http://jsbin.com/xapawoka/1/edit
Took your code and made a jsBin out of it. I can't see any problems whatsoever, so I'm assuming this is a simple typo somewhere in your code (could be the stray [ bracket at the top of your directive definition).
Here's the code:
var app = angular.module('app', []);
app.controller('ratingController',
function ($scope, $element, $attrs) {
console.log('ctrl.scope', $scope.url);
console.log('ctrl.attrs', $attrs.url);
});
app.directive('rating', function () {
return {
restrict: 'E',
scope: {
maxStars: '=',
url: '#'
},
controller: 'ratingController',
link: function (scope, el, attrs) {
console.log('dir.scope', scope.url);
console.log('dir.attrs', attrs.url);
}
};
});
And here's the output:
http://cl.ly/image/031V3W0u2L2w
ratingController is not asociated with your directive. Thus, there is no element which can hold attributes bound to that controller.
If you need to access those attributes, the link function is what you need (as you already mentioned above)
What exactly do you want to achieve?
I have multiple AngularJS directives that are nearly identical - there are only two differences: the template URL and one single element in the linking function. Both are constant for each directive. So, for simplicity's sake, this is how it looks like:
app.directive("myDirective", [function() {
return {
templateUrl: "this/path/changes.html",
scope: true,
link: function(scope, element, attrs) {
var veryImportantString = "this_string_changes";
// a few dozen lines of code identical to all directives
}
};
}]);
Now, moving the linking function to a commonly available place is obvious. What is not so obvious to me is how to set that "very important string" on the scope (or otherwise pass it to the directive) without declaring it in the HTML.
Here's what I've tried.
app.directive("myDirective", [function() {
return {
templateUrl: "this/path/changes.html",
scope: {
veryImportantString: "this_string_changes"
},
link: someCommonFunction
};
}]);
Nope, apparently the scope config doesn't take values from nobody. I can bind a value coming from the HTML attribute, but this is precisely what I don't want to do.
Also tried this:
app.directive("myDirective", [function() {
return {
templateUrl: "this/path/changes.html",
veryImportantString: "this_string_changes",
scope: true,
link: function(scope, element, attrs) {
var veryImportantString = this.veryImportantString;
}
};
}]);
But alas, the linking function is then called with this set to something else.
I assume this might work:
app.directive("myDirective", [function() {
return {
templateUrl: "this/path/changes.html",
scope: true,
compile: function(element, attrs) {
// no access to the scope...
attrs.veryImportantString = "this_string_changes";
return someCommonFunction;
}
};
}]);
However, I am not 100% sure this is what I want either, as it reeks of being a dirty workaround.
What are my other options?
I have devised a completely different approach: using a factory-like function to spawn directives.
var factory = function(name, template, importantString) {
app.directive(name, [function() {
return {
scope: true,
templateUrl: template,
link: function(scope, element, attrs) {
var veryImportantString = importantString;
// directive logic...
}
};
}]);
};
Then, in order to create individual directives, I simply call:
factory("myDirective", "/path/to/template.html", "important");
factory("myDirective2", "/path/to/template2.html", "important2");
What about the following:
Before wherever you define someCommonFunction, add the line
var veryImportantString = "someOptionalDefault"
This then puts veryImportantString in scope of both your someCommonFunction and .directive()
Then you can change your directive code to:
app.directive("myDirective", [function() {
return {
templateUrl: "this/path/changes.html",
scope: true,
link: function(args){
veryImportantString = "thatUberImportantValue";
someCommonFunction(args);
}
};
}]);
Proof of concept fiddle