Handling click on transcluded content of an angularjs directive - javascript

So lets say I have a directive that looks like so:
(function () {
'use strict';
angular
.module('app')
.directive('foo', foo);
/* #ngInject */
function foo() {
var directive = {
restrict : 'E',
controller: controller,
controllerAs: 'vm',
link: link,
transclude : true,
replace : true,
bindToController: true,
scope: {},
template : '<div><div ng-transclude></div>'
};
return directive;
function controller() {
var vm = this;
vm.click = function () {
// do something, add class whatever
}
}
function link(scope, elem, attrs) {}
}
}());
Now if I use the directive like so:
<foo>
<button ng-click="vm.click()">Click me!</button>
</foo>
I wanted to access the click function of the directive, how do I do that?

The transcluded contents scope is not created as a child of it's directives scope if there directive itself is defined with an isolated scope.
See:
Why ng-transclude's scope is not a child of its directive's scope - if the directive has an isolated scope?
As such kwan245's answer is correct for your particular example.

remove scope: {} from directive declaration and it should works.

Related

Cannot pass boolean to directive with Angular

I'm trying to pass a boolean value from my controller into my isolated scope directive. When I console.log(attrs) from the directive's link function, the someBoolean attribute is a string, rendering the actual text "main.bool" instead of a true or false value. When I toggle the boolean value from the outer controller, I want it to be updated in the directive.
https://plnkr.co/edit/80cvLKhFvljnFL6g7fg9?p=preview
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
someBoolean: '='
},
templateUrl: 'myDirective.html',
link: function(scope, element, attrs) {
console.log(scope);
console.log(attrs);
},
controller: function($scope, $element, $attrs) {
console.log(this);
},
controllerAs: 'directiveCtrl',
bindToController: true
};
});
Controller
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.bool = true;
vm.change = function() {
vm.bool = !vm.bool;
}
});
The template
<div>
Inside directive: {{someBoolean}}
</div>
As you have attached your directive Controller to directiveCtrl instead of mainCtrl, you'll access the variable someBoolean using directiveCtrl.someBoolean.
In this case, change the HTML to:
<div>
Inside directive: {{directiveCtrl.someBoolean}}
</div>
Plunker.
Another solution would be to remove the bindToController property inside your directive. With this, you don't need to use the controller name before the variable. Working Plunker.
Read more about this bindToController feature here.

Pass directive attribute into linked controller?

I have a directive i'm using to do the same search filtering across multiple pages. So the directive will be using a service and get pretty hefty with code. Because of that I want to link to a controller instead of have the controller inside the directive like this:
.directive('searchDirective', function($rootScope) {
return {
restrict: 'E',
templateUrl:'searchtemplate.html',
controller: 'searchCtrl',
controllerAs: 'search'
};
});
I also want access to parent scope data inside the template, so I don't want to use a isolated scope.
Anyway here's what i'm not sure how to do. My directive looks like this:
<search-directive filter="foo"/>
How do I pass in the value in the filter attribute so that I can access it in my controller using $scope.filter or this.filter?
If I were using an isolated scope it'd be simple. If i had the controller in the same page I could use $attrs. But since i'm using a controller from another spot and don't want an isolated scope i'm not sure how to get the attrs values into the controller.
Any suggestions?
What about using the link function and passing the value to the scope?
return {
restrict: 'E',
templateUrl:'searchtemplate.html',
controller: 'searchCtrl',
controllerAs: 'search',
link: function (scope, element, attr) {
scope.filter = attr.filter;
}
};
searchDirective.js
angular
.module('searchDirective', []).controller('SearchCtrl', SearchCtrl)
.directive('SearchDirective', directive);
function directive () {
var directive = {
templateUrl:'searchtemplate.html',
restrict: "E",
replace: true,
bindToController: true,
controller: 'searchCtrl as search',
link: link,
scope: { filter:'=' } // <-- like so here
};
return directive;
function link(scope, element, attrs) {}
}
SearchCtrl.$inject = [
'$scope',
'$filter'];
function SearchCtrl(
$scope,
$filter) {
/** Init SearchCtrl scope */
/** ----------------------------------------------------------------- */
var vs = $scope;
// ....
Also I highly recommend checking out this AngularJS style guide, how you are writing your directive above is how I use to do it too. John Papa shows some way better ways: https://github.com/johnpapa/angular-styleguide
Directives:
https://github.com/johnpapa/angular-styleguide#directives
Controllers:
https://github.com/johnpapa/angular-styleguide#controllers
Flip the values of bindToController and scope around.
{
....
scope: true,
bindToController: { filter:'=' }
...
}
I have just hit the same issue over the weekend, and made a simple complete example here: bindToController Not Working? Here’s the right way to use it! (Angular 1.4+)

Accessing the controller associated with a directive instance

I have associated a controller with a directive like so:
return function MyDirective() {
return {
scope: {},
restrict: 'E',
template: template,
controller: 'myController',
replace: true,
};
};
If I want to access a method on the controller from the template, do I need to add the controller to a property on the scope?
Template:
<div>
<div>
<button ng-click="doSomething()">Do something.</button>
</div>
</div>
Controller:
function MyController() {}
MyController.prototype.doSomething() {
window.alert('foo');
}
You should avoid scope: {} from your directive to access controller functions because of scope: {} in your directive create isolate scope from your controller.
That's why you may can not access controller functions from your directive template.
after avoid scope: {} use functions like normal controller functions.
Like:
<button data-ng-click="myFunction()">call my function</button>
you can use scope in link function in your directive.
link: function (scope, element, attrs)

Calling a function inside the controller of directive

Is it possible to call the method defined inside the directive controller from outside.
<div ng-controller="MyCtrl">
<map></map>
<button ng-click="updateMap()">call updateMap()</button>
</div>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
controller: function(){
$scope.updateMap = function(){
//ajax call here.
}
},
link: function($scope, element, attrs) {
$scope.updateMap();
//do some dom transformation
}
}
});
I want to call the method updateMap() function from my view.
If you expose the function on the controller, instead of the scope, you can expose the controller on the parent scope, such as:
controller: function($scope, $element, $attrs){
// Verify this. The controller has to be added to the parent scope, if the directive itself is creating a scope
$scope.$parent[$attrs["name"]]=this;
this.updateMap = function(){
//ajax call here.
}
},
Now in the main controller you will be able to access the controller:
<button ng-click="myMap.updateMap()">call updateMap()</button>
This is similar to how ng-model exposes its controller. Think of the controller as an API to your directive.
It would be a bad practice to access a function from the controller as you want. But still you can bind the updateMap function to $rootScope thus it can be used globally and still pass the current scope as a parameter to it.
Eg,
$rootScope.updateMap = function($scope) {
// use the scope to do the manipulation
}
<div ng-controller="MyCtrl">
<map></map>
<button ng-click="updateMap(this)">call updateMap()</button>
</div>
Here passing 'this' in updateMap function will refer to the scope in which the element is wrapped. In the above example, 'this' will refer to the MyCtrl's $scope
I would suggest two options. One simple option is to use events:
<div ng-controller="MyCtrl">
<map></map>
<button ng-click="updateMap()">call updateMap()</button>
</div>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
controller: function(){
$scope.updateMap = function(){
//ajax call here.
}
},
link: function($scope, element, attrs) {
$scope.$on('my.update.map.event', $scope.updateMap);
}
}
});
app.controller('MyCtrl', function ($scope) {
$scope.updateMap = function () {
$scope.$broadcast('my.update.map.event');
};
});
This isn't a bad solution. You're not polluting the root scope (#Krishna's answer) and your map directive isn't adding an arbitrary value to your controller's scope (#Chandermani's answer).
Another option, if you want to avoid events, is to to use the controllerAs syntax to expose your map directive's controller.
<div ng-controller="MyCtrl">
<map controller="mapController"></map>
<button ng-click="mapController.updateMap()">call updateMap()</button>
</div>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
scope: {
'controller': '=?'
},
template: '<div></div>',
//controllerAs creates a property named 'controller' on this
//directive's scope, which is then exposed by the
//'scope' object above
controllerAs: 'controller',
controller: function(){
this.updateMap = function(){
//ajax call here.
}
},
link: function($scope, element, attrs, ctrl) {
ctrl.updateMap();
}
}
});
This is similar to #Chandermani's answer, but the coupling between your controller and your directive is much more explicit. I can tell from the view that the map directive is exposing its controller and that it will be called mapController in MyCtrl's scope.
(I found this idea here).

Directive Inside another directive. Controller can't watch

I have 2 simple directives...
the parent directive:
.directive('modal', [function () {
return {
replace: true,
scope: {
/* attributes */
},
templateUrl: 'modal.tpl.html',
transclude: true,
link: function (scope) {
/* code */
}
};
the child directive
.directive('keypad', function () {
'use strict';
return {
templateUrl: 'keypad.tpl.html',
scope: {
value: '=',
},
link: function (scope, element, attrs) {
/* code */
}
};
and finally the controller:
.controller('ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
$scope.$watch('howMuch', function(){
console.log('wont work ;-(');
});
}
and my template looks like this:
<div modal>
<div keypad class="keypad" value="howMuch"></div>
</div>
Any idea why the child directive can't change the howMuch value on the controller?
The same code but WITHOUT the parent directive works PERFECT.
The parent directive has an isolate scope. You didn't show the scope attributes, but howMuch needs to be accessed via a property in your isolated scope in order to update the value in the controller's scope.

Categories

Resources