I'm looking at this code:
app.directive('resizer', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
angular.element($window).on('resize', function () {
$window.innerWidth > 500 ?
elem.addClass('large') : elem.removeClass('large')
});
}
}
}]);
Source: SO Link
I want to place this into a separate file, so in my app dependencies I've done:
var app = angular.module('app', [.....])
.directive("resizer", resizer)
and then in that new file I've written:
var resizer = function() {
return {
restrict: 'A',
link: function (scope, elem, attires, $window) {
angular.element($window).on('resize', function () {
$window.innerWidth > 500 ?
elem.addClass('large') : elem.removeClass('large')
});
}
}
}
However its not working - could someone help me understand whats wrong here please.
Thanks.
you can do it with the following:
angular.module('app').directive('resizer', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
angular.element($window).on('resize', function () {
$window.innerWidth > 500 ?
elem.addClass('large') : elem.removeClass('large')
});
}
}
}]);
you just have to initialize your module before somewhere with its dependencies:
angular.module('app', [.....]);
a reason why your code is not working, might be you named the directive wrong. in the first example you wrote resizer, in the 2nd one you named it resize.
Related
Is it possible to have a parent directive and a child directive, both with their own controller?
Something like:
.controller('ParentController', function () {
var self = this;
self.action = function () {
console.log('parent action');
}
})
.controller('TestSomethingController', function () {
var self = this;
self.something = function () {
console.log('something');
}
})
.directive('parent', function () {
return {
restrict: 'A',
controller: 'ParentController',
link: function (scope, element, attrs, controller) {
controller.action();
}
}
})
.directive('test', function () {
return {
restrict: 'A',
require: 'parent',
controller: 'TestSomethingController',
link: function (scope, element, attrs, controller) {
controller.something();
}
};
});
I tried to do this one codepen like this:
http://codepen.io/r3plica/pen/bdygeP?editors=101
If I remove the require, it obviously works, but I would like to keep the require.
Does anyone know if that is possible?
You can require multiple directives. Have it require itself as well as parent. With this syntax, the last parameter of link will be an array of the controllers of the given directives.
.directive('test', function () {
return {
restrict: 'A',
require: ['parent', 'test'],
controller: 'TestSomethingController',
link: function (scope, element, attrs, controllers) {
controllers[0].action(); // parent
controllers[1].something(); // self
}
};
});
Here is a forked, working version of your CodePen.
I try to use Flexisel with Angular but it fails to work somehow.
Here's plnkr link
var app = angular.module('angular.controls.flexSlider', [])
app.directive('flexCarousel', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
var options = scope.$eval($(element).attr('data-options'));
console.log(options);
$(element).flexisel(options);
}
};
});
I have forked your plunk, please check the fixes there. http://plnkr.co/edit/zH4u3MwkD6HX39I8PFEr?p=preview
You need a template for your directive in first case:
var app = angular.module('angular.controls.flexSlider', [])
app.directive('flexCarousel', function () {
return {
restrict: 'E',
transclude : true,
template : "<ng-transclude></ng-transclude>",
scope : {
options : "="
},
link: function (scope, element, attrs) {
$('#flexisel').flexisel(scope.options);
}
};
});
I am trying to convert number into currency suppose if user enter 5 in textbox i want to auto correct it like $5.00 for that i am trying to write directive but no idea how to make it work as working on directive for fist time.
(function () {
'use strict';
angular.module('commonModule')
.directive('srCurreny', function (utilSvc) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, model) {
element.bind('blur', function (event) {
var val = element.val();
if (!utilSvc.isEmptyOrUndefined(val)) {
var transform = currency + " " + val.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
model.$setViewValue(element.val(transform));
scope.$apply();
}
});
}
};
});
})();
JS
Set the amount in the Controller first.
angular.module('commonModule')
.controller('aController', ['$scope', function (scope) {
scope.amount = 5;
}])
.directive('srCurrency', ['$filter', function ($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, el, attrs, ngModel) {
function onChangeCurrency () {
ngModel.$setViewValue($filter('currency')(ngModel.$viewValue, '$'));
ngModel.$render();
}
el.on('blur', function (e) {
scope.$apply(onChangeCurrency);
});
}
}
}]);
HTML
<div ng-app='app' ng-controller="aController">
<input type="text" sr-currency ng-model='amount' />
</div>
JSFIDDLE
I recommend using the build-in currency filter of Angular, or, if that doesn't meet your needs you can create your own.
https://docs.angularjs.org/api/ng/filter/currency
I have a directive defined as following -
.directive('codesection', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: { current: '=', parent: '=', index: '=', params: '=' },
controller: ['Messages', '$scope', 'Modals', 'framewidth', '$http', '$rootScope', function (Messages, $scope, Modals, framewidth, $http, $rootScope) {
//code
}],
link: function (scope, element, attr) {
element.bind('mouseover', function (ev) {
ev.stopPropagation();
var wrappers = angular.element(document.getElementsByClassName('codesection'));
angular.forEach(wrappers, function (value, key) {
angular.element(value).children('span').removeClass('br');
});
element.children('.codesection').children('span').addClass('br');
});
},
compile: function (tElement, tAttr, transclude) {
var contents = tElement.contents().remove();
var compiledContents;
return function (scope, iElement, iAttr) {
if (!compiledContents) {
compiledContents = $compile(contents, transclude);
}
compiledContents(scope, function (clone, scope) {
iElement.append(clone);
});
};
},
templateUrl: './partials/directives/codesection.html',
replace: true
}
}])
The issue I am having is that Link functions is never called. Thank you!
P.S. The reason for the Compile logic is that the directive is recursive.
If you mean that link: function (scope, element, attr) { isn't called then it's pretty clear: The compile function already returns a link function. What is defined as link: doesn't matter anymore and is ignored.
I have attempted the following which seems to generate the correct html, but doesn't perform the data binding i.e. the new directives that I add do not have access to the $modelValue in ngController:
.controller('MyController', ['$scope', function($scope) {
$scope.aModel = {"key": "value"}
function init() {
$scope.aModel = {"key": "value"}
}
}])
.directive('innerDirective', [function (){
return {
restrict: 'AE',
require: 'ngModel',
template: '<ul></ul>',
link: function(scope, elem, attr, ngModelController) {
console.log(ngModelController.$modelValue) // Doesnt work
}
}
}])
.directive('outerDirective', ["$log", "$compile", function($log, $compile) {
return {
restrict: 'AE',
require: 'ngModel',
scope: {},
template: '<div></div>',
link: function(scope, elem, attrs, ngModelController) {
ngModelController.$render = function() {
var aModel = ngModelController.$modelValue; // Works
var modelName = attrs['ngModel']; // aModel
var html = '<inner-directive ng-model="' + modelName + '"></inner-directive>';
var angularElement = angular.element(html);
elem.append(angularElement);
$compile(angularElement)(scope);
}
}
};
}])
HTML looks like:
<div ng-controller="MyController">
<outer-directive ng-model="aModel"></outer-directive>
</div>
This is based on reccomendations from another question: Adding ngModel to input with a directive
What is it that I'm doing wrong here?
Cheers.
There is two issue:
1- outerDirective is using isolated scope. so aModel value is undefinded in the directive scope.
2-You can't access ngModelController.$modelValue in link function immediately. Look at outerDirective that you access it in the render function.
So you can change your directives as follows:
var app = angular.module('app', []);
app.controller('MyController', ['$scope', function ($scope) {
$scope.aModel = { "key": "value" }
function init() {
$scope.aModel = { "key": "value" }
}
}]);
app.directive('innerDirective', ['$timeout', function ($timeout) {
return {
restrict: 'AE',
require: 'ngModel',
template: '<ul></ul>',
link: function (scope, elem, attr, ngModelController) {
$timeout(function () {
console.log(ngModelController.$modelValue) // It works
});
}
}
}]);
app.directive('outerDirective', ["$log", "$compile", function ($log, $compile) {
return {
restrict: 'AE',
require: 'ngModel',
template: '<div></div>',
link: function (scope, elem, attrs, ngModelController) {
ngModelController.$render = function () {
var aModel = ngModelController.$modelValue; // Works
var modelName = attrs['ngModel']; // aModel
var html = '<inner-directive ng-model="' + modelName + '"></inner-directive>';
var angularElement = angular.element(html);
elem.append(angularElement);
$compile(angularElement)(scope);
}
}
};
}]);