I'm trying to build a really basic Angular directive that generates a "div" that can have two states: "on" and "off".
I've naively come up with an implementation that you can find here: http://jsfiddle.net/wSz2f/
The initial display is correct but the visual state is not updated when the scope state changes.
Here is the Angular directive definition:
var test = angular.module("test", []);
test.directive("led", function()
{
return {
restrict: "E",
replace: true,
template: "<div class='led led-off' ng-class='{ \"led-on\": isOn }'>{{isOn}}</div>",
link: function(scope, element, attributes, controller)
{
scope.isOn = false;
element.bind("click", function()
{
scope.isOn = !scope.isOn;
});
}
};
});
I guess I'm doing something stupid but what...?
Moreover, in term of design, am doing it the "Angular way" or is there better practices?
Thanks for any input. :)
Final edit:
Thanks to Mark, Bertrand and James for their input:
you have to either call scope.$apply() after updating the "isOn" property to make Angular aware of its change (thinking about it this is how it works too in other frameworks like WPF/Silverlight with the INotifyPropertyChanged interface, but not in Flex with all its magic binding) or use ng-click like suggested by Bertrand
you have to provide "ng-class" a condition for each CSS class
In your case you have to fire the digest
element.bind("click", function()
{
scope.isOn = !scope.isOn;
scope.$apply();
});
or even better, you could use the ng-click directive in your template to change the state of isOn.
var test = angular.module("test", []);
test.directive("led", function()
{
return {
restrict: "E",
replace: true,
template: "<div class='led led-off' ng-class='{ \"led-on\": isOn, \"led-off\": !isOn }' ng-click='onOff()'>{{isOn}}</div>",
link: function(scope, element, attributes, controller)
{
scope.isOn = false;
scope.onOff = function () {
scope.isOn = !scope.isOn;
}
}
};
});
Here is a fiddle
You're code looks good. You are missing the scope.$appy(); after updating the data. The exact internal reasons of why you need to call scope.$apply(); are only partly clear to me. I've read a few articles on it but am no expert yet.
Updated fiddle: http://jsfiddle.net/wSz2f/1/
Reading: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
Related
I am trying to understand the Slider directive provided here.
myApp.directive('slider', function() {
return {
restrict: 'A',
scope: {
ngModel: '='
},
link: function(scope, elem, attrs) {
console.log(scope.ngModel);
return $(elem).slider({
range: "min",
animate: true,
value: scope.ngModel,
slide: function(event, ui) {
return scope.$apply(function(){
scope.ngModel = ui.value;
});
}
});
}
};
});
Like purpose of ngmodel, range, animate, value:scope.ngModel etc. I have read some article about the same from here but this seems to be a little complicated for me.
This is a typical isolated scope directive configuration that is using a jQuery plugin .
scope.ngModel is passed in to the directive through the matching attribute ng-model in the html.
The '=' makes it a 2 way binding to it's parent.
As for the slider it is a jQuery UI slider and the options like animate and range etc are documented in their API
$apply() is used whenever events outside of angular context are used to modify scope. Angular needs to be told to run a digest to update the view
I'm working with Angular and I'm having trouble doing something that I normally use jQuery for.
I want to bind a click event to an element and on click, slide a sibling element down and up.
This is what the jQuery would look like:
$('element').click(function() {
$(this).siblings('element').slideToggle();
});
Using Angular I have added an ng-click attribute with a function in my markup:
<div ng-click="events.displaySibling()"></div>
And this is what my controller looks like:
app.controller('myController', ['$scope', function($scope) {
$scope.events = {};
$scope.events.displaySibling = function() {
console.log('clicked');
}
}]);
So far this is working as expected but I don't know how to accomplish the slide. Any help is very much appreciated.
Update
I have replaced what I had with a directive.
My markup now looks like this:
<div class="wrapper padding myevent"></div>
I have removed what I had in my controller and have created a new directive.
app.directive('myevent', function() {
return {
restrict: 'C',
link: function(scope, element, attrs) {
element.bind('click', function($event) {
element.parent().children('ul').slideToggle();
});
}
}
});
However, I still can't get the slide toggle to work. I don't believe slideToggle() is supported by Angular. Any suggestions?
I'm not sure exactly on the behaviour that you're talking about, but I would encourage you to think in a slightly different way. Less jQuery, more angular.
That is, have your html something like this:
<div ng-click="visible = !visible"></div>
<div ng-show="visible">I am the sibling!</div>
You can then use the build in ng-animate to make the sibling slide - yearofmoo has an excellent overview of how $animate works.
This example is simple enough that you can put the display logic in the html, but I would otherwise encourage you to as a rule to put it into the controller, like this:
<div ng-click="toggleSibling()"></div>
<div ng-show="visible"></div>
Controller:
app.controller('SiblingExample', function($scope){
$scope.visible = false;
$scope.toggleSibling = function(){
$scope.visible = !$scope.visible;
}
});
This kind of component is also a prime candidate for a directive, which would package it all up neatly.
app.directive('slideMySibling', [function(){
// Runs during compile
return {
// name: '',
// priority: 1,
// terminal: true,
// scope: {}, // {} = isolate, true = child, false/undefined = no change
// controller: function($scope, $element, $attrs, $transclude) {},
// require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
// template: '',
// templateUrl: '',
// replace: true,
// transclude: true,
// compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
link: function($scope, iElm, iAttrs, controller) {
iElm.bind("click", function(){
$(this).siblings('element').slideToggle();
})
}
};
}]);
Usage would be something like
<div slide-my-sibling><button>Some thing</button></div><div>Some sibling</div>
Note all the "code" above is just for the sake of example and hasn't been actually tested.
http://plnkr.co/edit/qd2CCXR3mjWavfZ1RHgA
Here's a sample Plnkr though as mentioned in the comments this isn't an ideal setup since it still has the javascript making assumptions about the structure of the view so ideally you would do this with a few directives where one requires the other or by using events (see $emit, $broadcast, $on).
You could also have the directive create the children "programmatically" via JavaScript and circumvent the issue of not knowing what context the directive is being used in. There are a lot of potential ways to solve these issues though none of the issues will stop it from functionally working they are worth noting for the sake of re-usability, stability, testing, etc.
As per this link : https://docs.angularjs.org/api/ng/function/angular.element
AngularJs element in your code snippet represents JQuery DOM object for related element. If you want to use JQuery functions, you should use JQuery library before angular loads. For more detail, please go through above link.
Best practice:
<div ng-if="view"></div>
$scope.view = true;
$scope.toggle = function(){
$scope.view = ($scope.view) ? false : true;
}
I have a small amount of js in the app.js file that I needed in order to manipulate the DOM in this Angular Grid:
http://plnkr.co/PXRgUA
You can see it in app.js.
$('.userRow ').live('click', function(e) {
$(this).find('span.userDetailRow.blueRow').show().animate({height:200},500);
});
$('.closeDetails').live('click', function(e) {
$(this).parent('span').animate({height:0}, 500).animate({height:0},500).hide();
e.stopPropagation();
});
How can I move this to a directive?
Does it have to be moved to a directive?
It does not seem right here.
Yes, you can (and should) move it to a directive. For the sake of clarity I'll include your old code here:
$('.userRow ').live('click', function(e) {
$(this).find('span.userDetailRow.blueRow').show().animate({height:200},500);
});
$('.closeDetails').live('click', function(e) {
$(this).parent('span').animate({height:0}, 500).animate({height:0},500).hide();
e.stopPropagation();
});
This (binding event listeners with jquery) is what people are chomping at the bit to describe as 'not the angular way.' Instead, you can use ng-click (which is just an inbuilt directive) to call javascript functions:
<tr row ng-click="expandRow()" ng-repeat="user in users" class="item-in-list el userRow" animate="fadeIn">
<span class="userDetailRow blueRow" style="display:none;"><span close ng-click="closeDetails(); $event.stopPropagation()">x</span>
You can see here there are two custom attributes defined on these elements. These link to the directives below. These directives have custom functions defined in their link function which you can then call with ng-click (though note that this is putting these functions on the global scope).
.directive('close', function() {
return {
restrict: 'A',
replace: false,
link: function($scope, element, attrs) {
$scope.closeDetails = function() {
$(element).parent('span').animate({height:0}, 500).animate({height:0},500).hide();
}
}
}
})
.directive('row', function() {
return {
restrict: 'A',
replace: false,
link: function($scope, element, attrs) {
$scope.expandRow = function() {
$(element).find('span.userDetailRow.blueRow').show().animate({height:200},500);
}
}
}
});
jQuery is still being used to here to locate and modify the elements for the sake of simplicity, so you can see where your old logic has gone. However you should ideally change this to use angular's inbuilt animation functionality. (more info on how animation works in the new angular version: http://www.yearofmoo.com/2013/08/remastered-animation-in-angularjs-1-2.html)
Plunker here:
http://plnkr.co/edit/UMvYnx?p=preview
In my understanding, $compile should be able to support nested directive compilation/link, but we came across an issue that the compilation/link is incomplete - only the outermost directive got rendered into DOM, and the issue only reproduced when both below conditions are true:
The inner directive template is loaded via templateUrl (e.g. async manner)
The compilation is triggered outside Angular context.
I wrote a jsfiddler to demo it, part code listed below, for complete case http://jsfiddle.net/pattern/7KjWP/
myApp.directive('plTest', function($compile){
return {
restrict :'A',
scope: {},
replace: true,
template: '<div>plTest rendered </div>',
link: function (scope, element){
$('#button1').on('click', function(){
var ele;
ele = $compile('<div pl-shared />')(scope);
console.log('plTest compile got : '+ ele[0].outerHTML);
// scope.$apply();
element.append(ele);
});
}
};
});
myApp.directive('plShared', function($compile, $timeout){
return {
restrict: 'A',
scope: {},
replace: true,
link: function (scope, element){
// comment out below line to make render success
//$timeout(function(){});
var el = $compile('<div pl-item></div>')(scope);
console.log('plShared compile got:' + el[0].outerHTML);
element.append(el);
}
};
});
myApp.directive('plItem', function($timeout){
return {
restrict: 'A',
scope:{},
template:'<div>plItem rendered <div pl-avatar/></div>',
link: function(scope){
}
};
});
myApp.directive('plAvatar', function(){
return {
restrict: 'A',
scope: {}
, templateUrl: 'avatar.html'
// ,template: 'content of avatar.html <div pl-image></div>'
};
});
Interestingly, i can workaround the issue by either calling scope.$apply() somewhere after compile() call (line 27)
or adding $timeout(function(){}) call into the link func of one of inner directive (line 41). Is this a defect or by design?
$(foo).on(bar, handler) is a jQuery event, which means AngularJS does not know the specifics of it, and will not (can not) run an apply-digest cycle after it to process all the bindings.
scope.$apply was made for this, and as you rightly say, fixes it. The rule of thumb is: if you implement UI functionality in an AngularJS application using other libraries (specifically: outside of apply-digest cycles), you must call scope.$apply yourself.
HTH!
After element.append(el), try to compile again as you have just modified the DOM.
You could try something such as $compile(element)(scope); or $compile(element.contents())(scope);.
As said before me, I would also change the event handler as follows :
$('#button1').on('click', function(){
scope.$apply( function(){
//blablalba
});
});
Also, justa piece of advice in case you would want to minify your code, I would declare the compile dependency using the following syntax :
.directive('directiveName',['$service1',''$service2,...,'$compile', function($service1, $service2,...,$compile){
//blablabla
}]}
Angular newbie here. I am trying to figure out what's going wrong while passing objects to directives.
here's my directive:
app.directive('walkmap', function() {
return {
restrict: 'A',
transclude: true,
scope: { walks: '=walkmap' },
template: '<div id="map_canvas"></div>',
link: function(scope, element, attrs)
{
console.log(scope);
console.log(scope.walks);
}
};
});
and this is the template where I call the directive:
<div walkmap="store.walks"></div>
store.walks is an array of objects.
When I run this, scope.walks logs as undefined while scope logs fine as an Scope and even has a walks child with all the data that I am looking for.
I am not sure what I am doing wrong here because this exact method has worked previously for me.
EDIT:
I've created a plunker with all the required code: http://plnkr.co/edit/uJCxrG
As you can see the {{walks}} is available in the scope but I need to access it in the link function where it is still logging as undefined.
Since you are using $resource to obtain your data, the directive's link function is running before the data is available (because the results from $resource are asynchronous), so the first time in the link function scope.walks will be empty/undefined. Since your directive template contains {{}}s, Angular sets up a $watch on walks, so when the $resource populates the data, the $watch triggers and the display updates. This also explains why you see the walks data in the console -- by the time you click the link to expand the scope, the data is populated.
To solve your issue, in your link function $watch to know when the data is available:
scope.$watch('walks', function(walks) {
console.log(scope.walks, walks);
})
In your production code, just guard against it being undefined:
scope.$watch('walks', function(walks) {
if(walks) { ... }
})
Update: If you are using a version of Angular where $resource supports promises, see also #sawe's answer.
you may also use
scope.walks.$promise.then(function(walks) {
if(walks) {
console.log(walks);
}
});
Another solution would be to add ControllerAs to the directive by which you can access the directive's variables.
app.directive('walkmap', function() {
return {
restrict: 'A',
transclude: true,
controllerAs: 'dir',
scope: { walks: '=walkmap' },
template: '<div id="map_canvas"></div>',
link: function(scope, element, attrs)
{
console.log(scope);
console.log(scope.walks);
}
};
});
And then, in your view, pass the variable using the controllerAs variable.
<div walkmap="store.walks" ng-init="dir.store.walks"></div>
Try:
<div walk-map="{{store.walks}}"></div>
angular.module('app').directive('walkMap', function($parse) {
return {
link: function(scope, el, attrs) {
console.log($parse(attrs.walkMap)(scope));
}
}
});
your declared $scope.store is not visible from the controller..you declare it inside a function..so it's only visible in the scope of that function, you need declare this outside:
app.controller('MainCtrl', function($scope, $resource, ClientData) {
$scope.store=[]; // <- declared in the "javascript" controller scope
ClientData.get({}, function(clientData) {
self.original = clientData;
$scope.clientData = new ClientData(self.original);
var storeToGet = "150-001 KT";
angular.forEach(clientData.stores, function(store){
if(store.name == storeToGet ) {
$scope.store = store; //declared here it's only visible inside the forEach
}
});
});
});