How to bind a directive from the Controller into the HTML? - javascript

Suppose i have a directive CARD
.directive('card', [function() {
return {
restrict: 'E', // Element directive,
templateUrl: 'scripts/directives/card.html'
};
and a controller say CARDCONTROLLER
.controller('cardController',function($scope){
$scope.directivename = 'card';
});
and a HTML file say CARD.HTML
<div>
<{{directivename}}></{{directivename}}>
</div>
But the above doesnot work.
Does any one have any idea about how to accomplish this?
EDIT.
I dont want to generate the directive dynamically.Its just that i want to bind it through the controller without/with changing anything in directive

you must add the controller to your directive.
.directive('card', function() {
return {
restrict: 'E', // Element directive,
templateUrl: 'scripts/directives/card.html',
controller: 'cardController'
}
})
this should do the trick.

call your directive like,
<div>
<data-card>
// add code
</data-card>
</div>

You can define controller in your directive also
.directive('myDirective', function() {
return {
restrict: 'E',
templateUrl: 'scripts/directives/card.html',
controller: function($scope) {
//write your controller code here
},
controllerAs: 'myController'
};
});

see the below snippet , you will get idea how you can do this.
var app = angular.module('myapp',[]);
app.directive('card',function() {
return {
restrict: 'E', // Element directive,
template: '<h5>I am directive template</h5>'
};
});
app.controller('cardController',function($scope,$compile,$element){
$scope.directivename = 'card';
var template = $compile("<"+$scope.directivename+"/>")($scope);
$element.append(template);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="cardController">
</div>

Related

How to call a directive's function from the controller on Angular

I have a directive that controls a personalized multiselect. Sometimes from the main controller I'd like to clear all multiselects. I have the multiselect value filling a "filter" bidirectional variable, and I am able to remove content from there, but when doing that I also have to change some styles and other content. In other words: I have to call a method belonging to the directive from a button belonging to the controller. Is that even posible with this data structure?:
(By the way, I found other questions and examples but their directives didn't have their own scope.)
function MultiselectDirective($http, $sce) {
return {
restrict: 'E',
replace: true,
templateUrl: 'temp.html',
scope: {
filter: "=",
name: "#",
url: "#"
},
link: function(scope, element, attrs){
//do stuff
scope.function_i_need_to_call = function(){
//updates directtive template styles
}
}
}
}
The best solution and the angular way - use event.
Live example on jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleOneController', function($scope) {
$scope.raise = function(val){
$scope.$broadcast('raise.event',val);
};
})
.controller('ExampleTwoController', function($scope) {
$scope.raise = function(val){
$scope.$broadcast('raise.event',val);
};
})
.directive('simple', function() {
return {
restrict: 'A',
scope: {
},
link: function(scope) {
scope.$on('raise.event',function(event,val){
console.log('i`m from '+val);
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ExampleApp">
<div ng-controller="ExampleOneController">
<h3>
ExampleOneController
</h3>
<form name="ExampleForm" id="ExampleForm">
<button ng-click="raise(1)" simple>
Raise 1
</button>
</form>
</div>
<div ng-controller="ExampleTwoController">
<h3>
ExampleTwoController
</h3>
<form name="ExampleForm" id="ExampleForm">
<button ng-click="raise(2)" simple>
Raise 2
</button>
</form>
</div>
</body>
I think better solution to link from controller to directives is this one:
// in directive
return {
scope: {
controller: "=",
},
controller: function($scope){
$scope.mode = $scope.controller.mode;
$scope.controller.function_i_need_to_call = function(){}
$scope.controller.currentState = state;
}
}
// in controller
function testCtrl($scope){
// config directive
$scope.multiselectDirectiveController = {
mode: 'test',
};
// call directive methods
$scope.multiselectDirectiveController.function_i_need_to_call();
// get directive property
$scope.multiselectDirectiveController.currentState;
}
// in template
<Multiselect-directive controller="multiselectDirectiveController"></Multiselect-directive>

Set controller and controllerAs to the same string

Say you have an AngularJS directive in which you want to set the controller attribute and the controllerAs attribute to the same string.
Ex.
angular.module('blahModule', [])
.directive('blahDirective', function(){
return {
restrict: 'E',
controller: 'blahController',
controllerAs: 'blahController',
templateUrl: 'blah/blah.html'
}
});
The above is valid and works, but it feels redundant to when setting the controller and controllerAs value to the same thing. Is there way to do it in one attribute? Like:
angular.module('blahModule', [])
.directive('blahDirective', function(){
return {
restrict: 'E',
controllerAndControllerAs: 'blahController',
templateUrl: 'blah/blah.html'
}
});
Thanks in advance!
You can use
controller: 'blahController as blahController',

Access parent controller from ng-included HTML

I want to access a function in a controller from an ng-included html, which contains a directive with an html template.
Meaning, given parent html template with controller:
<div ng-controller="profileCtrl">
<div ng-include src="profileContent"></div>
</div>
profileCtrl:
$scope.profileContent = '/html/views/myview.html';
$scope.test = 'This should show';
myview.html:
<my-directive></my-directive>
myDirective:
angular
.module('myModule')
.directive('myDirective', [function () {
return {
restrict: 'E',
templateUrl: '/html/directives/myDirectiveTemplate.html',
...
myDirectiveTemplate.html:
{{test}} //should output "This should show"
How can I access $scope.test from the child myDirective?
myDirectiveTemplate.html:
<form ng-submit="$parent.updateProfile()">
profileCtrl:
$scope.updateProfile = function() {
console.log('updating profile'); //not called
Try like this
{{$parent.test}}

How to get a value passed to a directive

i read Angularjs documentation .thereare examples for defining directives without passing a value.for example:
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
templateUrl: 'my-customer.html'
};
});
and HTML is
<div ng-controller="Controller">
<div my-customer></div>
</div>
but i want to create a directive like ng-model in which an attribute get passed.for example
<div ng-controller="Controller">
<div my-customer="Hello"></div>
</div>
i want to retrieve this hello in my directive definition link function.How to achieve that ??
You can pass as many as attributes and can access them directly using third argument in link function. Here you go:
.directive('myCustomer', function() {
return {
templateUrl: 'my-customer.html',
link: function(scope, element, attr) {
console.log('Attribute:', attr.myCustomer, attr.otherData);
}
};
});
<div my-customer="hello" other-data="foo"></div>
Just scroll a lil more in docs (Angular Directives) where you got above code, you will get how to get your answer attr of directive
.directive('myCustomer', function() {
return {
templateUrl: function(elem, attr){
...
//attr will be having the value
return attr;
}
};
If you want to use isolated scope, then you can do this:
.directive('myCustomer', function() {
return {
scope: {
myCustomer : '=' //If expected value is an object use '='. If it is just text, use '#'
}
templateUrl: 'my-customer.html',
link: function(scope, ele, attr){
console.log(scope.myCustomer);
}
};
});
If you don't want to use isolated scope, then
.directive('myCustomer', function($parse) {
return {
templateUrl: 'my-customer.html',
scope: true,
link: function(scope, ele, attr){
// if expected value is object
var hello = $parse(attr.myCustomer)(scope);
// if expected value is just text
var hello = attr.myCustomer;
}
};
});

Setting template or templateUrl in Angular Directive based on user input

I have simple directive like this :
app.directive('sample',function(){
return{
restrict:'E',
template:'Hello sample',
templateUrl:''
}
});
i want when user declare templateUrl in tag like this :
<sample template="some url"></sample>
use templateUrl but if nothing set use default template in directive
template and templateUrl can be specified as functions taking two arguments - tElement and tAttrs.
An easy way is to move your default template and perform your logic in the templateUrl function:
app.directive("sample", [
function() {
var defaultTemplate = 'default.html';
return {
restrict: 'E',
templateUrl: function (tElement, tAttrs) {
return tAttrs.template || defaultTemplate;
}
}
}
]);
Demo: http://plnkr.co/edit/rrPicuzzb6YF4Z6yh3Rn?p=preview
I suggest using transclude:
app.directive('sample',function(){
return {
restrict:'E',
transclude: true,
template:'Hello sample <div ng-transclude></div>
};
});
HTML
<sample>
<div ng-include="some url"></div>
</sample>

Categories

Resources