I have a list of items which are a custom directive and each of those items has a remove button. Now I want to disable this remove button when there is only one item left in my list, but for some reason it doesn't work as expected.
I've made a plunker example where you an watch this behavior.
I guess there is something wrong with the canRemove: '&' part of my directive. But I don't know how to get it working.
View:
<body ng-controller="MainCtrl as vm">
<div ng-repeat="item in vm.items">
<my-directive item="item"
canRemove="vm.items.length != 1"
remove="vm.remove(item)">
</my-directive>
</div>
</body>
Controller:
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.items = [
{
number: 1
} , {
number: 2
}
];
vm.remove = function(item) {
vm.items.splice(vm.items.indexOf(item), 1);
}
});
Directive:
app.directive('myDirective', function() {
return {
restrict: 'EA',
scope: {
item: '=',
canRemove: '&',
remove: '&'
},
controller: function() {
var vm = this;
vm.onRemove = function() {
vm.remove({ item: vm.item });
};
},
controllerAs: 'vm',
bindToController: true,
template: '<button ng-disabled="!vm.canRemove" ng-click="vm.onRemove()">' +
' Remove {{ vm.item.number }}' +
'</button>'
}
});
PS: Since I'm pretty new to angular is the way I'm handling the removing of the items a good practice? Or should I use broadcast and on instead?
First of all attribute should look like can-remove:
<my-directive item="item" can-remove="vm.items.length > 1" remove="vm.remove(item)"></my-directive>
Then in scope configuration you need to use = binding instead of &:
scope: {
item: '=',
canRemove: '=',
remove: '&'
},
Demo: http://plnkr.co/edit/DlZafON6HEdoyhzvwNIh?p=preview
Related
I have angular select on main page once user select value i want these object values in directive e.g $scope.selectedFileSize.value and $scope.selectedFileSize.size so i can further implement logic in directive. Any idea ?
main.html
<div class="col-md-3">
<select class="form-control" ng-model="selectedFileSize" ng-options="item as item.value for item in FileSizeOptions" ng-change="onSizeChange()"><option value="">Select</option></select>
</div>
<progress-bar-custom message="event"></progress-bar-custom>
Controller.js
$scope.onSizeChange = function(){
$scope.maxMb = $scope.selectedFileSize.size;
$scope.maxBytes = 3000;
$scope.max = $scope.maxBytes;
$scope.FileSizeString = $scope.selectedFileSize.value;
console.log('FileSize',$scope.maxMb);
}
directive.js
angular.module("App").directive('progressBarCustom', function() {
return {
restrict: 'E',
scope: {
message: "="
},
templateUrl: '/view/partials/progressbar.html',
controller: function($scope) {
var data = $scope.message;
var currentFileBytes = [];
var currentBytesSum;
$scope.maxBytes = 3000; // how to get these values from controller
$scope.max = $scope.maxBytes;
$scope.FileSizeString = $scope.selectedFileSize.value; //How can i get these values from controller.
$scope.random = function(value) {
$scope.dynamic = value;
$scope.downloadPercentage = parseFloat((value / $scope.maxBytes) * 100).toFixed(0);
console.log('current value-dynamic', $scope.dynamic);
};
}
});
You can define them as bindings in your directive scope:
scope: {
message: "=",
objToBind: "=" // add this one
},
And in HTML:
<progress-bar-custom message="event" obj-to-bind="selectedFileSize"></progress-bar-custom>
Then you could access it in your directive controller:
$scope.FileSizeString = $scope.objToBind.value
EDIT
I guess you want to dynamically change $scope.FileSizeString when your select is changed, right? Then I think you need to $watch in directive, otherwise it's always the initial value, and you won't aware of the changes in the future.
I don't know exactly how you implement your app, so I wrote a simple demo that demonstrate the key points:
I moved your default select option into ng-options array, and instead use ng-init to set default option.
I use $watch in directive to observe the binding's value change.
var app = angular.module('myApp', [])
app.controller('myCtrl', ['$scope', function($scope) {
$scope.fileSizes = [
{size: -1, value: 'Select'},
{size: 1, value: '1MB'},
{size: 2, value: '2MB'},
{size: 3, value: '3MB'}
]
$scope.onSizeChange = function() {
console.log($scope.selected.size)
}
}])
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
selectedSize: '='
},
template: '<div style="font-family:monospace"><p><b>Your choice:</b> {{myChoice}}</p><p><b>Actual Choice:</b> {{selectedSize}}</p></div>',
controller: function($scope) {
$scope.myChoice = ''
$scope.$watch('selectedSize', function (newVal, oldVal) {
$scope.myChoice = (newVal && newVal.size !== -1) ? newVal.value : ''
})
}
}
})
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<select ng-options="opt as opt.value for opt in fileSizes"
ng-model="selected"
ng-init="selected = fileSizes[0]"
ng-change="onSizeChange()">
</select>
<my-directive selected-size="selected"></my-directive>
</div>
</div>
Pass your required object through the isolate scope
HTML
<progress-bar-custom message="event" file="selectedFileSize"></progress-bar-custom>
JS
restrict: 'E',
scope: {
message: "=",
file: "="
},
templateUrl: '/view/partials/progressbar.html',
Since you have created an isolate scope in your directive, it is not normally recommended to use the $parent property, but rather to identify which variables you want to use from your parent scope. I would recommend that you pass in the variables you want to include in your directive in your html like so:
<progress-bar-custom message="event" fileSize="selectedFileSize.size" fileValue="selectedFileSize.value"></progress-bar-custom>
Then, in your directive in your scope attribute, you can add the variables.
scope: {
message: "=",
fileSize: "=",
fileValue: "="
},
You can use :-
scope.$parent.propertyName
inside your controller to access $scope level variables
I am new to AngularJS and I am trying to create directive which contains another directive inside.
Here how first directive look like
(
function () {
app.directive("cmEventBar", function () {
var controller = function () {
var vm = this;
vm.events = [
{name: "Truckdriver1", eventId: 1 },
{name: "Truckdriver2", eventId: 1 },
{name: "Truckdriver3", eventId: 1 }
];
}
return {
templateUrl: "app/shared/eventsBar/eventBar.html",
restrict: "E",
controller: controller,
priority: 1000,
terminal: true,
controllerAs: "vm",
scope: {}
};
});
})();
Inside html of this directive I am using ng-repeat to show all events. Insinde ng-repeat I have another directive:
<div ng-repeat="item in vm.events">
<cm-single-event name="{{item.name}}" eventId="{{item.eventId}}"></cm-single-event>
</div>
Here how second directive look like:
(function () {
app.directive("cmSingleEvent", function () {
var controller = function () {
var vm = this;
vm.info = switchEvent(eventId);
}
return {
template: "<li class={{vm.info.itemClass}}> {{vm.name}} {{vm.info.messege}} </li>",
restrict: "E",
controller: controller,
controllerAs: "vm",
scope: {
name: "=",
eventId: "="
}
};
});
})();
The output is a little weird because event has 3 elements and in output I see only one element + there are no vm.info from directive inside.
Output
{{vm.name}} {{vm.info.messege}}
What am I doing wrong here?
Thanks in advance!
As you are using = for name & eventId, you should not use {{}} while assigning there value in attribute & cmSingleEvent directive should have bindToController: true to retrieve value from isolated scope to controller this(context)
<cm-single-event name="item.name" event-id="item.eventId"></cm-single-event>
Assume I have a simple directive:
angular.module('app').directive('myDir', myDir);
function myDir() {
var directive = {
bindToController: true,
controller: null,
controllerAs: 'vm',
template: '<button ng-click="vm.myDirVar = 1">',
scope: {
myDirVar: '='
}
};
return directive;
}
If in the following example vm.var is undefined, my directive will not bind it to the isolated scope.
<my-dir my-dir-var="vm.var"></my-dir>
So in order to make it work, I'm using ng-init to set the default value for thevm.var, after that the binding to isolated scope works.
<my-dir my-dir-var="vm.var" ng-init="vm.var = var || 0"></my-dir>
The question is, how can I improve my directive so I can get rid of the ng-init while vm.var would still be binding even if it is undefined initially.
You can do something like:
var directive = {
bindToController: true,
controller: function(){
this.myDirVar = this.myDirVar || 0;
},
controllerAs: 'vm',
template: '<button ng-click="vm.myDirVar = 1">',
scope: {
myDirVar: '='
}
};
If is not a problem having a controller.
I want to create a directive that has dynamic view with dynamic controller. the controller and the template view is coming from the server.
The Directive
var DirectivesModule = angular.module('BPM.Directives', []);
(function () {
'use strict';
angular
.module('BPM.Directives')
.directive('bpmCompletedTask', bpmCompletedTask);
bpmCompletedTask.$inject = ['$window'];
function bpmCompletedTask ($window) {
// Usage:
// <bpmCompletedTask></bpmCompletedTask>
// Creates:
//
var directive = {
link: link,
restrict: 'E',
scope: {
type: '=',
taskdata: '=',
controllername:'#'
},
template: '<div ng-include="getContentUrl()"></div>',
controller: '#',
name: 'controllername'
};
return directive;
function link(scope, element, attrs) {
scope.getContentUrl = function () {
return '/app/views/TasksViews/' + scope.type + '.html';
}
scope.getControllerName = function ()
{
console.warn("Controller Name is " + scope.type);
return scope.type;
}
}
}
})();
Here how I'm trying to use the directive
<div ng-controller="WorkflowHistoryController as vm">
<h2>Workflow History</h2>
<h3>{{Id}}</h3>
<div ng-repeat="workflowStep in CompletedWorkflowSteps">
<bpm-completed-task controllername="workflowStep.WorkflowTaskType.DataMessageViewViewName" taskdata="workflowStep.WorkflowTaskOutcome.TaskOutcome" type="workflowStep.WorkflowTaskType.DataMessageViewViewName">
</bpm-completed-task>
</div>
</div>
The problem now is when the directive gets the controller name it get it as literal string not as a parameter.
Is it doable ?
if it's not doable, What is the best solution to create dynamic views with its controllers and display them dynamically inside ng-repeat?
Thanks,
Update 20 Jan I just updated my code in case if some one interested in it. All the Credit goes to #Meligy.
The First Directive:
(function () {
'use strict';
angular
.module('BPM.Directives')
.directive('bpmCompletedTask', bpmCompletedTask);
bpmCompletedTask.$inject = ['$compile', '$parse'];
function bpmCompletedTask ($compile, $parse) {
var directive = {
link: function (scope, elem, attrs) {
console.warn('in the first directive - before if');
if (!elem.attr('bpm-completed-task-inner'))
{
console.warn('in the first directive');
var name = $parse(elem.attr('controllername'))(scope);
console.warn('Controller Name : ' + name);
elem = elem.removeAttr('bpm-completed-task');
elem.attr('controllernameinner', name);
elem.attr('bpm-completed-task-inner', '');
$compile(elem)(scope);
}
},
restrict: 'A',
};
return directive;
}
})();
The Second Directive
angular
.module('BPM.Directives')
.directive('bpmCompletedTaskInner',['$compile', '$parse',
function ($window, $compile, $parse) {
console.warn('in the second directive');
return {
link: function (scope, elem, attrs) {
console.warn('in the second directive');
scope.getContentUrl = function () {
return '/app/views/TasksViews/' + scope.type + '.html';
}
},
restrict: 'A',
scope: {
type: '=',
taskdata: '=',
controllernameinner: '#'
},
template: '<div ng-include="getContentUrl()"></div>',
controller: '#',
name: 'controllernameinner'
};
}]);
The Html
<div ng-repeat="workflowStep in CompletedWorkflowSteps">
<div bpm-completed-task controllername="workflowStep.WorkflowTaskType.DataMessageViewViewName" taskdata="workflowStep.WorkflowTaskOutcome.TaskOutcome"
type="workflowStep.WorkflowTaskType.DataMessageViewViewName">
</div>
</div>
Update:
I got it working, but it's really ugly. Check:
http://jsfiddle.net/p6Hb4/13/
Your example has a lot of moving pieces, so this one is simple, but does what you want.
Basically you need a wrapper directive that takes the JS object and converts into a string property, then you can use هى your directive for everything else (template, scope, etc).
.
Update 2:
Code Inline:
var app = angular.module('myApp', []).
directive('communicatorInner', ["$parse", "$compile",
function($parse, $compile) {
return {
restrict: 'A',
template: "<input type='text' ng-model='message'/><input type='button' value='Send Message' ng-click='sendMsg()'><br/>",
scope: {
message: '='
},
controller: '#'
};
}
]).
directive('communicator', ['$compile', '$parse',
function($compile, $parse) {
return {
restrict: 'E',
link: function(scope, elem) {
if (!elem.attr('communicator-inner')) {
var name = $parse(elem.attr('controller-name'))(scope);
elem = elem.removeAttr('controller-name')
elem.attr('communicator-inner', name);
$compile(elem)(scope);
}
}
};
}
]).
controller("PhoneCtrl", function($scope) {
$scope.sendMsg = function() {
alert($scope.message + " : sending message via Phone Ctrl");
}
}).
controller("LandlineCtrl", function($scope) {
$scope.sendMsg = function() {
alert($scope.message + " : sending message via Land Line Ctrl ");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<div ng-app="myApp">
<div ng-init="test = {p: 'PhoneCtrl', l: 'LandlineCtrl' }">
<communicator controller-name="test.p" message="'test1'"></communicator>
<communicator controller-name="test.l"></communicator>
</div>
</div>
.
Original (irrelevant now but can help other related issues)
Yes, it should work.
A test with Angular 1.3:
http://jsfiddle.net/p6Hb4/9/
Things to check:
Is the controller defined and added to the module? It will not work
If the controller is just a global function it won't work. It has to be added via the <myModule>.controller("<controllerName>", <functiion>) API
Does ng-controller work? Just adding it to the template
Similarly, does using ng-controller directly outside of the directive work?
I have these nested directives the very inner of which has an 'X' sign, which is, when clicked, is supposed to delete an item (classic problem). Basically, the whole thing is a menu.
I have added an ng-click to the 'X' sign/button of the item, but i am very confused on how to link this whole thing back to the controller, so that i can call a deleteItem() function and actually remove the item. I also want to have scope for the sidebar-item separated (the original version of this code is slightly more elaborated and has conditional statements)
Here's what i have so far
The full working - i.e. not really working - version can be found in this jsfiddle
Here's the relevant part of HTML:
<div ng-app="demoApp">
<div ng-controller="sidebarController">
<div sidebar>
<div sidebar-item ng-repeat="item in items" item="item"></div>
</div>
<button ng-click="addItem();">Add Item</button>
</div>
</div>
And here's the JavaScript:
var demoApp = angular.module('demoApp', []);
demoApp.controller("sidebarController", ["$scope", function($scope) {
$scope.items = [
];
$scope.itemId = 1;
$scope.addItem = function() {
var inx = $scope.itemId++;
$scope.items.push( { id: inx, title: "Item " + inx, subTitle: "Extra content " + inx } );
};
$scope.deleteItem = function(item) {
console.log("Delete this!");
console.log(item);
};
}]);
demoApp.directive("sidebar", function() {
return {
restrict: "A",
transclude: true,
template: '<div><div ng-transclude></div></div>',
controller: ["$scope", function($scope) {
this.deleteItem = function(item) {
$scope.deleteItem(item);
$scope.$apply();
};
}]
};
});
demoApp.directive("sidebarItem", function() {
return {
restrict: "A",
scope: {
item: "="
},
require: "^sidebar",
template: '<div><span>{{ item.title }}</span><br /><span>{{ item.subTitle }}</span><br /><span ng-click="deleteItem(item)">X</span></div>',
};
});
Im sure the answer is simple, but I just cant find it.
If you want to use a required controller function you need to inject it into the link function
in sidebar-item add
link : function (scope, element, attrs, sidebar) {
scope.deleteItem = function (item) {
sidebar.deleteItem(item);
}
}