Custom directive Attribute - angularjs

In my custom directive im getting attributes values, in my case it could be numbers or arrays, but in my directtive im getting a string array (ex: "[1,2]".
How can i get my array in the attribute not being a string?
view:
<div my-directive to=[1,2]
directive:
angular.module('myApp')
.directive('myDirective',
[
'$http', '$q','$uibModal',
dir
]);
function dir($http, $q, UserService, $uibModal) {
return {
restrict: 'A',
link: function($scope, element, attrs, controller) {
element.on( 'click', function( evt ){
console.log(attrs.to);
});
}
};
}

Try following approach:
On view (init the directive & set the directive param)
<div ng-app='demo'>
<demo-directive to-val='[1,2,3,4,5]'></demo-directive>
</div>
On the directive
var demo = angular.module('demo', []);
demo.directive('demoDirective', function($parse) {
return {
restrict: 'E',
template: '<div ng-repeat="val in toVal">{{val}}</div>',
link: function (scope, element, attrs, controller) {
// parse the attribute array to a scope params
scope.toVal = JSON.parse(attrs.toVal);
}
}
});

Related

Access angular controller from directive using require

In a directive i want to require a controller but i get the error that the controller can't be found. I am sure it is a small thing or maybe it is not possible the way i want to do it.
angular.module('myApp', []);
angular.module('myApp').controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
//some function here returning data
}]);
angular.module('myApp').directive('yoloswag', function() {
return {
require: ['^?ngModel', '^GreetingController'],
restrict: 'A',
scope: {
},
link: function(scope, element, attrs, controllers) {
var modelCtrl = controllers[0],
greetingsCtrl = controllers[1];
console.log(controllers)
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="GreetingController">
{{ greeting }}
<div yoloswag>test</div>
</div>
</div>
What am i doing wrong?
Thank you so much!
Your code does not having and dependency with your main module, that's why you are getting that error.
Your code should be the following
angular.module('myApp', [])
.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
//some function here returning data
}])
.directive('yoloswag', function() {
return {
require: ['^?ngModel', '^GreetingController'],
restrict: 'A',
scope: {
},
link: function(scope, element, attrs, controllers) {
var modelCtrl = controllers[0],
greetingsCtrl = controllers[1];
console.log(controllers)
}
};
});
or set a variable for main module then you can add controller and directive with the main module like,
var MainModule = angular.module('myApp', []);
MainModule.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
//some function here returning data
}]);
MainModule.directive('yoloswag', function() {
return {
require: ['^?ngModel', '^GreetingController'],
restrict: 'A',
scope: {
},
link: function(scope, element, attrs, controllers) {
var modelCtrl = controllers[0],
greetingsCtrl = controllers[1];
console.log(controllers)
}
};
});
You can use controller property of directive :
make sure don't update property in link function.
return {
restrict: 'A',
scope: {
},
controller : 'GreetingController',
link: function(scope, element, attrs) {
var modelCtrl = controllers[0],
greetingsCtrl = controllers[1];
console.log(controllers)
}
};

Get ng-model from a input inside directive and put it in an attribute of directive

I have "nibTextbox" directive with an input inside it,input has a ng-model,I want that ng-model value always available in "value" attribute of directive.(I don't wanna use replace)
angular.module('nib', [])
.directive('nibTextbox', function () {
return {
restrict: 'E',
scope: {
id: '#',
title: '#',
},
compile: function (element, attributes) {
var linkFunction = function (scope, element, attributes) {
}
return linkFunction;
},
controller: ['$scope', '$http', function ($scope, $http) {
}],
template: '<div value="{{nibTextBoxValue}}"><img src="" alt=""/><label>{{title}}</label><input id="{{id}}_txt" type="text" ng-model="nibTextBoxValue"></input></div>'
};
});
<nib-textbox id="ngArmin1" title="ngArmin1Title" value="{{nibTextBoxValue}}"></nib-textbox>
value is not valid for a <div> element. So let's change it to data-div.
This is how it will look more or less (I usually work with typescript but I'll use plain javascript to pass the idea):
angular.module('nib', [])
.directive('nibTextbox', function () {
return {
restrict: 'E',
scope: {
id: '#',
title: '#',
},
compile: function (element, attributes) {
var linkFunction = function (scope, element, attributes) {
}
return linkFunction;
},
// Injected $element for manipulating attributes
controller: ['$scope', '$http', '$element', function ($scope, $http, $element) {
$scope.$watch("nibTextBoxValue", function(newValue) {
$element.attr("data-value", newValue);
});
}],
templateUrl: 'template.html' // Extracting the template to a file
};
});
The directive template (template.html):
<div>
<img src="" alt=""/><label>{{title}}</label>
<input id="{{id}}_txt" type="text" ng-model="nibTextBoxValue"></input>
</div>
In addition, remove the value attribute from your directive:
<nib-textbox id="ngArmin1" title="ngArmin1Title"></nib-textbox>
the answer:use $watch
change controller definition to this:
controller: ['$scope', '$http', '$element', function ($scope, $http, $element) {
$scope.$watch("nibTextBoxValue", function (nv) {
$element.attr("value", nv);
});
}]

AngularJS Missing required controller

I want to create two directives that have the following structure:
<div ng-app="myApp">
<div ui-foo="test">
<div ui-bar="test2"></div>
</div>
</div>
First directive is uiFoo, the second one is uiBar.
To define these directives I have setup the following module definition:
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.message = function() {
alert(1);
};
}
};
}
).directive('uiBar',
function() {
return {
restrict: 'A',
require: '^uiFoo',
scope: true,
link: function($scope, element, attrs, uiBarController) {
uiBarController.message();
}
};
}
);
angular.module('myApp', ['ui']);
The problem that I am experiencing is known as error/$compile/ctreq (Controller 'uiFoo', required by directive 'uiBar', can't be found!) and the documentation for it can be found here (https://docs.angularjs.org/error/$compile/ctreq?p0=uiFoo&p1=uiBar). I know, a little lackluster.
It doesn't seem to solve my issue.
I've created a JSFiddle for this which you can find here http://jsfiddle.net/A8Vgk/1187/
Thanks!
Like the error says, you're missing the controller on the uiFoo directive.
When you use the require: ^uiFoo, it tells Angular that you want to have access to the controller in the directive called uiFoo.
You didn't define a controller in that directive, so you get the error.
Just define the controller:
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.message = function() {
alert(1);
};
},
controller: function($scope) {
this.message = function () {
alert("works!");
}
}
};
}
)
Working Fiddle.

How can I get my directive to access the controllers scope

I have a setup like this:
<controller>
<directive>
in my controller that has a function that returns an html string. How can I get my directive to render this by accessing the controllers scope?
Or maybe I should just put the controller in the directive?
app.controller('controller', ['$scope', 'DataService', function ($scope, DataService) {
$scope.parseJson = function () {
//returns the html
};
}]);
directive
app.directive('Output', function () {
return {
restrict: 'A',
replace: true,
template: '<need html from controller>',
link: function(scope, element, attr) {
//render
//scope.parseJson();
}
};
});
You should use the isolated scope: '&' option
app.directive('output', ['$sce', function ($sce) {
return {
restrict: 'A',
replace: true,
template: "<div ng-bind-html='parsed'></div>",
scope:{
output: "&"
},
link: function(scope){
scope.parsed = $sce.trustAsHtml(scope.output());
}
};
}]);
Template:
<div output="parseJson()"></div>
The directive and the controller should be sharing the scope already. Don't bother using a template for the directive, just get the HTML string in you linking function (you already have the method call in there) and modify the element directly using element.html(). Take a look at the element docs for more info.
app.directive('Output', function ($compile) {
return {
restrict: 'A',
link: function(scope, element, attr) {
var templateString = scope.parseJson();
var compiledTemplate = $compile(templateString)(scope);
compiledTemplate.appendTo("TheElementYouWishtoAppendYourDirectiveTo");
}
};
});

Angular - directive link isnt called

I have wrote a directive which has a link function which isnt beeing called, the templae is injected to the DOM
function() {
'use strict';
// Define the directive on the module.
// Inject the dependencies.
// Point to the directive definition function.
angular.module('app').directive('nvVideo', ['$window', nvVideo]);
function nvVideo ($window) {
// Usage:
//
// Creates:
//
var directive = {
link: function(scope, element, attrs) {
alert('ggg');
},
restrict: 'EA',
template: '<div id="slot1">video slot</div>'
};
return directive;
}
})();
HTML
<div ng-app='app'>
<n-video></n-video>
</div>
Directive
angular.module('app', [])
.directive('nVideo', ['$compile', function ($compile) {
return{
restrict: 'EA',
template: '<div id="slot1">video slot</div>',
link: function(scope, element, attrs) {
alert('ggg');
}
}
}]);
JSFIDDLE

Resources