I'm learning AngularJS and I'm training for how to build a reusable directive.
The problem is that it works with an array with one element, but not with two or more.
The HTML tag is just: <breadcrumb></breadcrumb> which in case, render as expected. But, I need to do manually what "replace:true" would do.
The error is: parent is null.
I exhausted all Google searches looking for an example.
But my case is peculiar, because there is an <inner ng-repeat> inside <breadcrumb> which is an another inner-directive instead an normal tag, that's why replace doesn't work and I need to do manually.
There is a problem related to "dynamic template load..."
OBS: I tried to do in both "link:" and "compile:" the logic, same error...
I could make the code work, but, I'm unable to remove <inner> tag as transclude would do automatic.
Now the output is almost perfect, and I just need to remove the <inner>, but no luck until now. I tried to replace the element tag, but still no luck.
<ul class="breadcrumb">
<!-- I want to remove this <inner> and leave <li> alone! -->
<inner data-ng-repeat="_item in items track by $index" class="ng-scope">
<li class="ng-scope">1
</li>
</inner>
<!-- remove for clarity -->
</ul>
var myModule = angular.module("myModule", []);
myModule.directive('breadcrumb', function($timeout) {
"use strict";
var directiveDefinitionObject = {
template: '<ul class="breadcrumb"><inner data-ng-repeat="_item in items track by $index"></inner></ul>',
replace: true,
// transclude: true,
restrict: 'E',
scope: {},
controller: ["$scope", "$element", "$attrs", "$transclude", controller],
link: ["scope", "iElement", "iAttrs", link]
};
function link(scope, iElement, iAttrs) {
scope.addNewItem = function(new_item) {
scope._push(new_item);
}
}
function controller($scope, $element, $attrs, $transclude) {
$scope.items = [1, 2, 3, 4, 5];
$scope._push = function(item) {
$scope.items.push(item);
};
$scope._pop = function() {
$scope.items.pop();
};
$scope.is_last = function(item) {
return $scope.items.indexOf(item) == ($scope.items.length - 1);
}
}
return directiveDefinitionObject;
});
myModule.directive("inner", ["$compile",
function($compile) {
"use strict";
function getItemTemplate(index) {
return '<li>{{ _item }}</li>';
}
return {
require: "^breadcrumb",
restrict: "E",
compile: function compile(tElement, tAttrs)
{
return function postLink(scope, iElement, iAttrs)
{
iElement.html(getItemTemplate(0));
$compile(iElement.contents())(scope);
};
}
};
}
]);
You can just remove the compile function of yours in inner directive and set replace: true, because it's just mocking the default behavior of replace, as you stated. So you inner directive would become:
myModule.directive("inner", ["$compile",
function($compile) {
"use strict";
return {
replace: true
require: "^breadcrumb",
restrict: "E",
template: '<li>{{ _item }}</li>'
};
}
]);
But you have a problem that your items array is defined into your breadcrumb directive, what is wrong and will not let you make it reusable. You could bind it at scope definition with something like this:
<breadcrumb items="someItemsArrayFromParentScope"></breadcrumb>
...directive('breadcrumb', function() {
...
return {
...
scope: {
items: '='
}
}
});
This would create a two directional binding between the array from parent and internal widget scope. But going further, you might want to let the user define the inner elements of the breadcrumb, it would be as following:
myModule.directive('breadcrumb', function($timeout) {
var directiveDefinitionObject = {
template: '<ul class="breadcrumb" ng-transclude></ul>',
replace: true,
transclude: true,
restrict: 'E',
scope: {},
controller: ["$scope", "$element", "$attrs", "$transclude", controller]
};
function controller($scope, $element, $attrs, $transclude) {
$scope.addNewItem = function(new_item) {
$scope._push(new_item);
}
$scope._push = function(item) {
$scope.items.push(item);
};
$scope._pop = function() {
$scope.items.pop();
};
$scope.is_last = function(item) {
return $scope.items.indexOf(item) == ($scope.items.length - 1);
}
}
return directiveDefinitionObject;
});
myModule.directive("inner", function($compile) {
return {
require: "^breadcrumb",
restrict: "E",
template: '<li><a href="#" ng-transclude></a></li>',
replace: true,
transclude: true
};
}
);
And in your html you would come with:
<breadcrumb>
<inner ng-repeat="item in items"><i>{{item}}</i></inner>
</breacrumb>
The trick is the ng-transclude directive inside the templates. It just get the contents of the element and "move it" to inside the element marked with ng-transclude and link it against the parent scope, what is awesome, as you can have dynamic naming for the items that would be based on parent scope. The items of the ng-repeat, for example, would be defined in the parent scope, as expected. This is the preferred way, and you would even get the possibility of use different inner templates (as I did with the <i> tag). You would even be able to not use an ng-repeat and hardcode the inner elements, if it's the case:
<!-- language: lang-html -->
<breadcrumb>
<inner>First Path</inner>
<inner>Second Path: {{someParentScopeVariable}}</inner>
</breacrumb>
Here is a working Plnker.
I was able to rebuilt it.
I've learnt a lot since my first attempt.
The solution was simplified because the dynamic template is rubbish to handle, because ng-repeat does not redraw the entire array. So, I did it my own way and it was a clean solution.
Related
I'm wondering if there is a way to require the controller of a directive that exists/is nested somewhere as a common parent's child directive in AngularJS.
Directive Structure
Suppose I have the following structure for my directives:
<parent-directive>
<ul>
<li some-nested-directive ng-repeat="dir in directives"></li>
</ul>
<settings-menu></settings-menu>
</parent-directive>
Directive Definition
/*
* some-nested-directive directive definition
*/
.directive('someNestedDirective', function(){
// ...
return {
restrict: 'A',
controller: someNestedDirectiveController
};
});
/*
* settings-menu directive definition
*/
.directive('settingsMenu', function(){
return {
restrict: 'AE',
require: [], // how to require the nested-directive controller here?
link: function(scope, iElement, attrs, ctrls){
// ...
}
};
})
I've already checked out this SO question which states how to require controllers of directives that exist along the same line in a hierarchy.
But my question is regarding a way to do the same in a hierarchy of directives that NOT necessarily exist along the same line. And if this is not possible, what is a proper workaround for it. Any help would be appreciated.
EDIT
Also, can any of the prefixes for require (or a combination of them) be used to achieve the same?
One approach is to use parent directive as a way to pass references between controllers:
var mod = angular.module('test', []);
mod.directive('parent', function() {
return {
restrict: 'E',
transclude: true,
template: '<div>Parent <div ng-transclude=""></div></div>',
controller: function ParentCtrl() {}
}
});
mod.directive('dirA', function() {
return {
restrict: 'E',
template: '<div>Dir A <input type="text" ng-model="name"></div>',
require: ['dirA', '^^parent'],
link: function(scope, element, attrs, ctrls) {
//here we store this directive controller into parent directive controller instance
ctrls[1].dirA = ctrls[0];
},
controller: function DirACtrl($scope) {
$scope.name = 'Dir A Name';
this.name = function() {
return $scope.name;
};
}
}
});
mod.directive('dirB', function() {
return {
restrict: 'E',
template: '<div>Dir A <button ng-click="click()">Click</button></div>',
require: ['dirB', '^^parent'],
link: function(scope, element, attrs, ctrls) {
//let's assign parent controller instance to this directive controller instance
ctrls[0].parent = ctrls[1];
},
controller: function DirBCtrl($scope) {
var ctrl = this;
$scope.click = function() {
//access dirA controller through parent
alert(ctrl.parent.dirA.name());
};
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='test'>
<parent>
<dir-a></dir-a>
<dir-b></dir-b>
</parent>
</div>
When using above approach it also makes sense to encapsulate how the dirA controller is stored inside parent controller i.e. by using a getter property or by exposing only the required properties of dirA controller.
I aggree with miensol's reply and I recommend that approach but in some cases you may need something like that;
<parent-directive>
<ul>
<some-nested-directive id="snd1" ng-repeat="dir in directives"></some-nested-directive>
</ul>
<settings-menu some-nested-directive-id="snd1"></settings-menu>
You can access the scope of some-nested-directive using its id from the settings-menu;
$("#" + scope.someNestedDirectiveId).scope()
Once I used this approach to cascade the values of a dropdown according to the choise of another independent dropdown.
I have created two directives and inserted the first directive into the second one. The content of template attribute works fine but the scope variable of the controller is not recognized. Please provide me solution on this
sample link: http://jsbin.com/zugeginihe/2/
You didn't provide the attribute for the second directive.
HTML
<div second-dir first-dir-scope="content">
<div first-dir first-dir-scope="content"></div>
</div>
Link demo: http://jsbin.com/jotagiwolu/2/edit
The best option would using parent directive, We could take use of require option of directive like require: '?secondDir' in firstDir
Code
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope) {
$scope.content = "test1";
});
myApp.directive("firstDir", function() {
return {
restrict: "AE",
require: '?secondDir',
scope: {
firstDirScope: "="
},
template: "<div>first content</div>",
link: function(scope, element, attrs, secondDir) {
console.log(scope.firstDirScope, 'first');
}
};
});
myApp.directive("secondDir", function() {
return {
restrict: "AE",
scope: {
firstDirScope: "="
},
controller: function($scope) {
console.log($scope.firstDirScope, 'second');
}
};
});
Working JSBin
Below is the only way i could figure out how to get a directive to pull out an attribute from its origin element, get a new value by hitting a service, and then adding that new service method return as a class in the directive template. i'm wondering if there is an alternative pattern that might be cleaner then this pattern that might use ng-class or possibly ng-transclude:
html:
<my-directive data-condition="{{hour.condition}}"></my-directive>
js:
angular.module('myApp')
.directive('myDirective', function (myService) {
return {
transclude: true,
replace: true,
scope: true,
template: '<i class="{{wiIconClass}}"></i>',
restrict: 'E',
link: function($scope, $elm, attrs){
$scope.wiIconClass=myService.getValue(attrs.condition);
}
}
});
If your function myService.getValue is synchronous, you could simply do:
<div ng-class="getClass(hour.condition)">
And in your controller:
$scope.getClass = function(condition) {
return myService.getValue(condition);
}
Alternatively, you can directly put your service within your scope:
$scope.myService = myService;
So the HTML becomes
<div ng-class="myService.getValue(hour.condition)">
In both cases, you will need to inject your service into your controller:
myModule.controller('myController', function($scope, myService) {
// this controller has access to myService
})
I would use the Directives scope parameter instead of using the Directives Attribute values. This is because when using the attributes you will need to setup a $watch to see when that value updates, with using $scope you get the benefit of the binding aspect.
As far as to respond to the best way, its hard to say without knowing your actual task. You can have Angular update the elements css class value in several different ways.
Here's a working Plunker with some small updates to your existing code.
http://plnkr.co/edit/W0SOiBEDE03MgostqemT?p=preview
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.hour = {
condition: 'good'
};
})
.factory('myService', function() {
var condValues = {
good: 'good-class',
bad: 'bad-class'
};
return {
getValue: function(key) {
return condValues[key];
}
};
})
.directive('myDirective', function(myService) {
return {
transclude: true,
replace: true,
scope: {
condition: '='
},
template: '<i class="{{myService.getValue(condition)}}"></i>',
restrict: 'E',
link: function(scope, elm, attrs) {
scope.myService = myService;
}
};
});
In the following code, i change the object's property on clicking the 'tab' element, but the corresponding ngbind span is not getting updated. Do i have to call some function to update the view?
HTML:
<html ng-app="splx">
...
<body ng-controller="Application">
<span ng-bind="obj.val"></span>
<tabpanel selector="obj">
<div tab value="junk">junk</div>
<div tab value="super">super</div>
</tabpanel>
</body>
</html>
JS:
var cf = angular.module('splx', []);
function Application($scope) {
$scope.obj = {val: "something"};
}
cf.directive('tabpanel', function() {
return {
restrict: 'AE',
scope: {
selector: '='
},
controller: ['$scope', function($scope) {}]
};
});
cf.directive('tab', function() {
return {
require: '^tabpanel',
restrict: 'AE',
scope: true,
link: function(scope, elem, attrs) {
elem.bind('click', function() {
scope.$parent.selector.val = "newthing";
});
}
};
});
cf.directive('tab', function() {
return {
require: '^tabpanel',
restrict: 'AE',
scope: true,
link: function(scope, elem, attrs) {
elem.bind('click', function() {
scope.$apply(function () {
scope.$parent.selector.val = "newthing";
});
});
}
};
});
That works for me. Just missing a little scope.$apply in there.
Might want to have a look at https://coderwall.com/p/ngisma if you find yourself using/having trouble with '$apply already in progress'.
If you want to change the value to what you clicked on, I'd do something like this:
scope.$parent.selector.val = attrs.tab;
As opposed to:
scope.$parent.selector.val = "newthing";
And then you can change your markup to look like this:
<tabpanel selector="obj">
<div tab="junk">junk</div>
<div tab="super">super</div>
</tabpanel>
Hope that helps!
First problem: you are not binding your controller to your app.
You need cf.controller('Application', Application);.
Also you need ng-controller="Application" in HTML on a parent of that span and the tabpanel directive.
Second problem: after changing that scope variable in your click event you need to
scope.$apply() to let Angular know something changed and it needs to $digest it.
You can check out my version here.
I'm trying to acheive databinding to a value returned from a service inside a directive.
I have it working, but I'm jumping through hoops, and I suspect there's a better way.
For example:
<img my-avatar>
Which is a directive synonymous to:
<img src="{{user.avatarUrl}}" class="avatar">
Where user is:
$scope.user = CurrentUserService.getCurrentUser();
Here's the directive I'm using to get this to work:
.directive('myAvatar', function(CurrentUser) {
return {
link: function(scope, elm, attrs) {
scope.user = CurrentUser.getCurrentUser();
// Use a function to watch if the username changes,
// since it appears that $scope.$watch('user.username') isn't working
var watchUserName = function(scope) {
return scope.user.username;
};
scope.$watch(watchUserName, function (newUserName,oldUserName, scope) {
elm.attr('src',CurrentUser.getCurrentUser().avatarUrl);
}, true);
elm.attr('class','avatar');
}
};
Is there a more succinct, 'angular' way to achieve the same outcome?
How about this ? plunker
The main idea of your directive is like
.directive('myAvatar', function (CurrentUserService) {
"use strict";
return {
restrict: 'A',
replace: true,
template: '<img class="avatar" ng-src="{{url}}" alt="{{url}}" title="{{url}}"> ',
controller: function ($scope, CurrentUserService) {
$scope.url = CurrentUserService.getCurrentUser().avatarUrl;
}
};
});