AngularJS : Toggle to modify attribute in directive - angularjs

In the project I am working on, I am applying a ui-sort via Angular on a to-do list and am trying to get a toggle to work for when a user is editing tasks. My current method of testing this toggle is employing the use of a button to toggle sorting on and off.
My strategy is this:
Employ an angular directive to generate an initial template with sorting on.
Add a button which, when clicked, modifies a scope variable in the controller ($scope.sortingEnabled) to toggle between true and false.
Inside my directive, I have a watch set on 'sortingEnabled' in a link function to add/remove the sorting attribute from a .
Here is the in todo.html before I tried employing a directive:
sortableOptions is a function written to re-order the todos on internal records.
<ul class="unstyled" ng-model="todos" ui-sortable="sortableOptions">
<!-- list items here via ng-repeat -->
</ul>
The following is the code in todo.html after my directive:
<sortable></sortable>
And my current draft for the directive inside todo-directives.js:
app.directive('sortable', function() {
var innerHtml = '<li ng-repeat="todo in todos" class="item">' +
'<span ng-model="todo.name" >{{todo.name}}</span> ' +
'</li>';
var link = function (scope, element, attrs) {
scope.$watch('sortingEnabled', function() {
if(scope.sortingEnabled === true) {
element.contents().attr("ui-sortable", "sortableOptions");
//needed else ui-sortable added as a class for <ul> initially for
//some reason
element.contents().removeClass("ui-sortable");
}
else {
element.contents().removeAttr("ui-sortable");
//needed else ui-sortable added as a class for <ul> initially for
//some reason
element.contents().removeClass("ui-sortable");
}
});
};
return {
restrict: 'E',
transclude: true,
template: '<ul class="unstyled" ng-model="todos" ui-sortable="sortableOptions" ng-transclude>' + innerHtml + '</ul>',
link: link
};
});
This code works in the source code view of Chrome's debugger, but the view does not properly refresh. I have tried scope.$apply() within the watch function but get a $digest already running error. I have also tried $compile, but my understanding of how that works is severely lacking, so I get errors of which I do not remember.
Am I missing something crucial, or doing things incorrectly? I am unsure, as my understanding is low, being that I have been leaning Angular for a few weeks. Any help would be greatly appreciated!

The angular directive supports watching when the sortable options change:
scope.$watch(attrs.uiSortable, function(newVal, oldVal){
So all you had to do was look at the jqueryui sortable documentation, and update the correct property on the plugin.
Plunker: http://plnkr.co/edit/D6VavCW1BmWSSXhK5qk7?p=preview
Html
<ul ui-sortable="sortableOptions" ng-model="items">
<li ng-repeat="item in items">{{ item }}</li>
</ul>
<button ng-click="sortableOptions.disabled = !sortableOptions.disabled">Is Disabled: {{sortableOptions.disabled}}</button>
JS
app.controller('MainCtrl', function($scope) {
$scope.items = ["One", "Two", "Three"];
$scope.sortableOptions = {
disabled: true
};
});

Related

How to update Directive on State Changes

I have a root state that defines the overall structure of the Angular template. In the root state, I have the sidebar included that has dynamic menus via directive that changes based on the state. Like this:
.state(‘root', {
abstract: true,
url: ‘/root',
templateUrl: ‘views/root.html',
})
root.html includes the sidebar.html that has dynamic menu called through Directive like this:
sidebar.html
<ul class="nav" id="side-menu">
<li class="nav-header">
<img alt="avatar" ng-src="{{ avatar }}" />
</li>
<!—Dynamic Menus Directive -->
<li sidebar-menus></li>
</ul>
The directive shows the menu based on $state.includes(). But what happens is, the directive shows fine in the first load but it doesn’t update the directive during state changes. To resolve this, I tried the following methods but nothing worked:
Added the $state to scope in Main controller but it still doesn’t change the directive
once it is compiled first.
Tried adding $stateChangeSuccess watcher to trigger recompiling the directive, but it doesn’t
recompile again after the first time (or) maybe it is recompiling but the changes are not seen in the template (this is the code I have now
which I will give below).
Moving the sidebar inside separate child
states instead of having it in root state works, but it beats the
purpose since I am trying to load the overall structure in the root
state first and only refresh the menu sections in subsequent state
changes.
I am not really sure how to approach this. I have a feeling my approach can be out of whack and hoping someone can guide me here. This is my directive code at the moment:
.directive('sidebarMenus', ['$compile', '$state', '$rootScope',
function($compile, $state, $rootScope) {
return {
restrict: 'A',
replace: true,
link: function(scope, element, attrs) {
var state = scope.$state; // Scope from Main Controller
// HTML Template
function contructHtml(state) {
var htmlText = '';
// First Child State
if (state.includes('root.child1')) {
var htmlText = '<li>Child 1 Menu</li>';
}
// Second Child State
if (state.includes('root.child2')) {
var htmlText = '<li>Child 2 Menu</li>';
}
// Third Child State
if (state.includes('root.child3')) {
var htmlText = '<li>Child 3 Menu</li>';
}
$compile(htmlText)(scope, function( _element, _scope) {
element.replaceWith(_element);
});
}
$rootScope.$on('$stateChangeSuccess', function() {
var state = scope.$state; // scope.$state is added in main controller
contructHtml(state);
});
// Initial Load
contructHtml(state);
}
}
}])
You can get rid of the compile business by using template.
You template could look something like this:
<li ng-if="state.includes('root.child1')">Child 1 Menu</li>
<li ng-if="state.includes('root.child2')">Child 2 Menu</li>
<li ng-if="state.includes('root.child3')">Child 3 Menu</li>
So your directive code should look sth like this
return {
restrict: 'A',
replace: true,
template:'<div> <li ng-if="state.includes('root.child1')">Child 1 Menu</li>
<li ng-if="state.includes('root.child2')">Child 2 Menu</li>
<li ng-if="state.includes('root.child3')">Child 3 Menu</li>
</div>'
link: function(scope, element, attrs) {
$scope.state = scope.$state; // Scope from Main Controller
$rootScope.$on('$stateChangeSuccess', function() {
$scope.state = scope.$state; // scope.$state is added in main controller
});
}
}

creating a new directive with angularjs

so i'm making a simple directive called "hover", it's a basic nav menu that when you pass a mouse over a specific aba, this aba changes the color. See my script code:
var app = angular.module('myModule', []);
app.directive('hover', function(){
return{
restrict: 'E',
controller: function($scope) {
$scope.hover = null;
$scope.selected = null;
$scope.onHover = function (index){
$scope.hover = index;
}
$scope.mouseLeave = function(){
if($scope.selected)
$scope.hover = $scope.selected;
else
$scope.hover = -1;
}
$scope.onClick = function(index) {
$scope.hover = index;
$scope.selected = index;
}
},
compile: function(el, attrs){
el.children().attr('data-ng-mouseover', 'onHover('+attrs.index+')');
el.children().attr('data-ng-mouseleave', 'mouseLeave()');
el.children().attr('data-ng-click', 'onClick('+attrs.index+')');
el.children().attr('data-ng-class', '{'+ attrs.onhover +': hover == ' + attrs.index + ' || selected == ' + attrs.index + '}');
}
}
});
And now my html:
<ul>
<hover index="0" onhover="hover"><li>Home</li></hover>
<hover index="1" onhover="hover"><li>About Us</li></hover>
<hover index="2" onhover="hover"><li>Contact</li></hover>
<hover index="3" onhover="hover"><li>Share with us!</li></hover>
</ul>
This is working fine, but when i put my html in this way:
<ul>
<li hover index="0" onhover="hover">Home</li>
<li hover index="1" onhover="hover">About Us</li>
<li hover index="2" onhover="hover">Contact</li>
<li hover index="3" onhover="hover">Share with us!</li>
</ul>
This doesn't work, i have to wrap my "li" with "hover" tag to make this work(and yes, i'm changing the restrict property to "A"), why? And another question, wrapping my "li" with "hover" tag is a bad trick to validation my html?
This is my html compiled:
<ul>
<li onhover="hover" index="0" hover="" data-ng-mouseover="onHover()">Home</li>
<li onhover="hover" index="1" hover="" data-ng-mouseover="onHover()">About Us</li>
<li onhover="hover" index="2" hover="" data-ng-mouseover="onHover()">Contact</li>
<li onhover="hover" index="3" hover="" data-ng-mouseover="onHover()">Share with us!</li>
</ul>
When i pass the mouse over these elements, my function: "onHover" doesn't is called.
First a clarification..
I do not recommend overusing $compile, there are better ways for binding event listeners to a scope.
I solved this question for me to learn how compilation works and to share it with others.
what happens when manipulating template element inside a the compile function?
The compilation phase iterates down the DOM , from parent to children element.
When you manipulate children of a DOM element inside a compile function it happens before $compile got down to these children elements to collect their directives, so every change you make to the contents of the template element will be compiled and linked with the continuation of the compilation phase.
This is not the case when you manipulate the template element itself , then $compile will not look for more directives in that same element because it's only collecting directives once per each DOM element.
So these attributes you added are just not being compiled!
Lets $compile it manually:
I tried to add $compile(el) but my browser crashed (don't laugh at me), The reason is it got into a loop where it's infinitely compiling itself.
So I removed the directive attribute and then $compile again.
I set { priority:1001 } and { terminal:true }. This iss needed to prevent other directive compile functions to run before our directive or after out manual compiling.
Solution:
here is a plunker: http://plnkr.co/edit/x1ZeigwhQ1RAb32A4F7Q?p=preview
app.directive('hover', function($compile){
return{
restrict: 'A',
controller: function($scope) {
// all the code
},
priority: 1001, // we are the first
terminal: true, // no one comes after us
compile: function(el, attrs){
el.removeAttr('hover'); // must remove to prevent infinite compile loop :()
el.attr('data-ng-mouseover', 'onHover('+attrs.index+')');
el.attr('data-ng-mouseleave', 'mouseLeave()');
el.attr('data-ng-click', 'onClick('+attrs.index+')');
el.attr('data-ng-class', '{'+ attrs.onhover +': hover == ' + attrs.index + ' || selected == ' + attrs.index + '}');
var fn = $compile(el); // compiling again
return function(scope){
fn(scope); //
}
}
}
});

Ng-controller on same element as ng-repeat - no two-way-data-binding

I can't get two-way-data-binding to work in an Angular js ng-repeat.
I have an ng-controller specified on the same element that has the ng-repeat specified -
I just learnt that by doing this, I can get a hold of each item that is being iterated over by ng-repeat. Here is the HTML:
<div ng-controller="OtherController">
<div id="hoverMe" ng-controller="ItemController" ng-mouseenter="addCaption()"
ng-mouseleave="saveCaption()" ng-repeat="image in images">
<div class="imgMarker" style="{{image.css}}">
<div ng-show="image.captionExists" class="carousel-caption">
<p class="lead" contenteditable="true">{{image.caption}}</p>
</div>
</div>
</div>
</div>
And here is the ItemController:
function ItemController($scope){
$scope.addCaption = function(){
if($scope.image.captionExists === false){
$scope.image.captionExists = true;
}
}
$scope.saveCaption = function(){
console.log($scope.image.caption);
}
}
And the OtherController:
function OtherController($scope){
$scope.images = ..
}
When I hover the mouse over the #hoverMe-div - the caption-div is added correctly. But when I input some text in the paragraph and then move the mouse away from the #hoveMe-div, the $scope.image-variables caption value is not updated in the saveCaption-method. I understand I'm missing something. But what is it?
You don't need a ng-controller specified on the same element that has the ng-repeat to be able to get each item.
You can get the item like this:
<div ng-repeat="image in images" ng-mouseenter="addCaption(image)" ng-mouseleave="saveCaption(image)" class="image">
And in your controller code:
$scope.addCaption = function (image) {
if(!image.captionExists){
image.captionExists = true;
}
};
To get contenteditable to work you need to use ng-model and a directive that updates the model correctly.
Here is a simple example based on the documentation:
app.directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, controller) {
element.on('blur', function() {
scope.$apply(function() {
controller.$setViewValue(element.html());
});
});
controller.$render = function(value) {
element.html(value);
};
}
};
});
Note that the directive probably needs more logic to be able to handle for example line breaks.
Here is a working Plunker: http://plnkr.co/edit/0L3NKS?p=preview
I assume you are editing the content in p contenteditable and are expecting that the model image.caption is update. To make it work you need to setup 2 way binding.
2 way binding is available for element that support ng-model or else data needs to be synced manually. Check the ngModelController documentation and the sample available there. It should serve your purpose.

AngularJS directive only when the condition is true

I am going to have a contextmenu directive in ng-repeat items.
Based on whether a condition is true, the directive should be applied.
How do I put a condition like only when item.hasMenu == true then apply the directive ?
<ul ng-controller="ListViewCtrl" >
<li contextmenu ng-repeat="item in items">{{item.name}} </li>
</ul>
EDIT
This seems to have worked for me. First the directive.
app.directive('menu',function(){
return {
restrict : 'A',
link : function(scope,element,attrs){
if(scope.hasMenu){
element.contextmenu({
menu:[
{title:"Remove" , "cmd" : "remove"},
{title:"Add" , "cmd" : "add"},
],
select:function(event,ui){
//alert("select " + ui.cmd + " on" + ui.target.text());
if (ui.cmd ==='remove'){
alert('Remove selected on ' + scope.item);
}
if (ui.cmd ==='add'){
alert("Add selected");
}
}
});
}
}
}
}
);
Then the html
<ul ng-controller="ListViewCtrl" >
<li menu ng-repeat="item in items">{{item.name}} </li>
</ul>
Can you do something like this, using ng-if?
<ul ng-controller="ListViewCtrl" >
<li ng-repeat="item in items">
<span>{{item.name}}</span>
<div contextmenu ng-if="item.hasMenu"></div>
</li>
</ul>
Here are the docs for ng-if.
EDIT:
If you are driving the context menu off of a class, you should be able to do this:
<ul ng-controller="ListViewCtrl" >
<li ng-class="{'hasmenu': item.hasMenu}" ng-repeat="item in items">{{item.name}} </li>
</ul>
I think this is pretty tricky if you don't want to change your DOM structure. If you could just place your contextmenu directive on a sub DOM node inside the <li> things would be a lot easier.
However, let's assume you can't do that and let's also assume that you don't own the contextmenu directive so that you can't change it to your needs.
Here is a possible solution to your problem that might be a bit hackish (actually I don't know!)
'use strict';
angular.module('myApp', [])
.controller('TestController', ['$scope', function($scope) {
$scope.items = [
{name:1, hasMenu: true},
{name:2, hasMenu: false },
{name:3, hasMenu: true}
];
}])
.directive('contextmenu', function(){
return {
restrict: 'A',
link: function(scope, element){
element.css('color', 'red');
}
}
})
.directive('applyMenu', ['$compile', function($compile){
return {
restrict: 'A',
link: function(scope, element){
if (scope.item.hasMenu){
//add the contextmenu directive to the element
element.attr('contextmenu', '');
//we need to remove this attr
//otherwise we would get into an infinite loop
element.removeAttr('apply-menu');
//we also need to remove the ng-repeat to not let the ng-repeat
//directive come between us.
//However as we don't know the side effects of
//completely removing it, we add it back after
//the compile process is done.
var ngRepeat = element.attr('ng-repeat');
element.removeAttr('ng-repeat');
var enhanced = $compile(element[0])(scope);
element.html(enhanced);
element.attr('ng-repeat', ngRepeat);
}
}
}
}]);
I faked the contextmenu directive to just change the color to red just so that we can see it's taking place.
Then I created an apply-menu attribute directive. This directive than checks if the hasMenu property is true and if so hooks in and adds the contextmenu directive and does a manual $compile process.
However, what worries me a bit about this solution is that I had to temporally remove the ng-repeat directive (and also the apply-menu directive) to get the $compile process to act the way we want it to act. We then add the ng-repeat directive back once the $compile has been made. That is because we don't know the side effects of removing it entirely from the resulting html. This might be perfectly valid to do, but it feels a bit arkward to me.
Here is the plunker: http://plnkr.co/edit/KrygjX
You can do this way
angularApp.directive('element', function($compile) {
return {
restrict: 'E',
replace: true,
transclude: true,
require: '?ngModel',
scope: 'isolate',
link: function($scope, elem, attr, ctrl) {
$scope.isTrue = function() {
return attr.hasMenu;
};
if($scope.isTrue())
//some html for control
elem.html('').show();
else
//some html for control
elem.html('').show();
$compile(elem.contents())($scope);
}
};
});

unable to make custom html with angular tags work with select2

I am using angular-ui's ui-select2. I want to add custom html formatting to the selections. Select2 allows this by specifying the formatSelection in its config.
I have html with angular tags as below that I want to use for formatting the selection-
var format_code = $compile('<div ng-click="showHide=!showHide" class="help-inline"><div style="cursor: pointer;" ng-show="!!showHide" ng-model="workflow.select" class="label">ANY</div><div style="cursor: pointer;" ng-hide="!!showHide" ng-model="workflow.select" class="label">ALL</div></div>')( $scope );
var format_html = "<span>" + data.n + ' : ' + data.v +' ng-bind-html-unsafe=format_code'+ "</span>"
$scope.select_config = {
formatSelection: format_html
}
If I compile the html as in above and assign it, I just see an [object,object] rendered in the browser. If I dont compile it, I see the html rendered properly, but the angular bindings dont happen, ie the clicks dont work.
Any ideas what is wrong?
I had the same problem, select2 loading in a jquery dialog and not using the options object I would give it.
What I ended up doing is isolating the element in a directive as following:
define(['./module'], function (module) {
return module.directive('dialogDirective', [function () {
return {
restrict: 'A',
controller: function ($scope) {
console.log('controller gets executed first');
$scope.select2Options = {
allowClear: true,
formatResult: function () { return 'blah' },
formatSelection: function () { return 'my selection' },
};
},
link: function (scope, element, attrs) {
console.log('link');
scope.someStuff = Session.someStuff();
element.bind('dialogopen', function (event) {
scope.select2content = MyResource.query();
});
},
}
}]);
and the markup
<div dialog-directive>
{{select2Options}}
<select ui-select2="select2Options" style="width: 350px;">
<option></option>
<option ng-repeat="item in select2content">{{item.name}}</option>
</select>
{{select2content | json}}
</div>
What is important here:
'controller' function gets executed before html is rendered. That means when the select2 directive gets executed, it will already have the select2Options object initialized.
'link' function populates the select2content variable asynchronously using the MyResource $resource.
Go on and try it, you should see all elements in the dropdown as "blah" and selected element as "my selection".
hope this helps, that was my first post to SO ever.

Resources