Calling a function inside the controller of directive - javascript

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).

Related

Update scope from a directive on mousedown Angularjs

I am having an issue updating the scope in a controller from a directive. Below are the basics of what is going on.
myApp.directive('myDirective', ['$document', function($document) {
return {
link: function(scope, element, attr, controller) {
angular.element(element).bind('mousedown', function(event){
scope.name = 'test';
});
}
}
}
myApp.controller('myController', ['$scope', function($scope){
$scope.name = 'something';
}]);
The html:
<p>{{name}}</p>
<p my-directive>Click me</p>
The result above is always something that was set in my controller, and is never updated to test.
I have tried a $watch in my controller but it never updates, so i have to be just missing something...
Since you are using jQuery .bind functionality you have to use scope.$apply to notify Angular that you have updated a scope property.
angular.module('app', [])
.directive('myDirective', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
angular.element(element).bind('mousedown', function(event) {
scope.$apply(function() {
scope.name = 'test';
});
});
}
}
})
.controller('ctrl', function($scope) {
$scope.name = 'something';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<p>{{name}}</p>
<p my-directive>Click Me</p>
</div>
Directives have their own isolated scope. If you want to share something between a directive's scope and a controller's scope, you need to include it in the directive definition like this:
return {
scope: {
name: '='
},
link: function(scope, element, attr, controller) {
angular.element(element).bind('mousedown', function(event){
scope.name = 'test';
});
}
}
This tells Angular that you want to share the scope variable name between the directive and whatever scope calls that directive. Using the equal sign (=) defines it as two-way data binding.

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.

Bind to model from child directive where model has not been resolved at compile-time

I am using angular ui for bootstrap for its modals:
http://angular-ui.github.io/bootstrap/#/modal
I am opening a modal with a controller and templateUrl with:
var modalInstance = $uibModal.open({
animation: true,
templateUrl: $scope.templateUrl,
controller: $scope.controller,
size: 'lg',
resolve: {
formModel: item
}
});
where formModel is the model I will use in the modal.
Here is the controller for the modal:
app.controller('commentCtrl', ['$scope', '$modalInstance', 'formModel', function ($scope, $modalInstance, formModel) {
$scope.formModel = {};
var loadFormModel = function () {
if (formModel !== undefined) {
$scope.formModel = formModel;
}
};
loadFormModel();
}]);
This modal has child directives and needs to pass properties of formModel to them
template:
<div>
<child model="formModel.Comment"></child>
</div>
but child is created before the modal's controller has loaded formModel. Inside the child I want to use model as:
app.directive('child', function () {
return {
restrict: 'E',
template: '<textarea ng-model="model"></textarea>',
link: linkFn,
controller: controllerFn,
scope: {
model: '='
}
};
});
Edit:
I've found that I can do:
<div>
<child model="formModel" property="Comment"></child>
</div>
...
app.directive('child', function () {
return {
restrict: 'E',
template: '<textarea ng-model="model[property]"></textarea>',
link: linkFn,
controller: controllerFn,
scope: {
model: '=',
property: '#'
}
};
});
Is there a better way to do this without the extra attribute?
Edit 2:
I have found where the bug is:
http://plnkr.co/edit/kUWYDvjR8YArdqtQRHhi?p=preview
See fItem.html for some reason having any ng-if causes the binding to stop working. I have put a contrived ng-if='1===1' in for demonstration
This happens because ng-if directive creates new inherited scope, so the bug is just a common scope prototypal inheritance pitfall.
The most concise way to get around it is to use controllerAs syntax in conjunction with bindToController, the avoidance of undesirable scope inheritance side effects is the most common use case for them. So it will be
app.directive('fItem', function () {
return {
restrict: 'E',
replace: true,
templateUrl: 'fItem.html',
controller: ['$scope', function ($scope) {
}],
controllerAs: 'vm',
bindToController: true,
scope: {
model: '='
}
};
});
and
<div class="input-group">
<textarea ng-if='1===1' ng-model="vm.model" class="form-control"></textarea>
</div>
Not sure what you are trying to do. If you need just to wait until variable is resolved, you need just use promise: (Here is simple one using $timeout, if you use i.e. $http - you ofc dont need $q and $timeout)
resolve: {
something: function () {
return $q(function(resolve, reject) {
setTimeout(function() {
resolve('Hello, world!');
}, 3000);
});
Then modal will be opened only after promise is resolved.
http://plnkr.co/edit/DW4MzIO4ej0JorWRgWIK?p=preview
Also keep in mind that you can wrap you object, so if in scope you have $scope.object = {smth : 'somevalue'} :
resolve: {
object: function () {
return $scope.object;
});
And in modal controller:
$scope.object = object;
Now object in initial controller scope and object in modal scope point to same javascript object, so any time you change one - another changes. You are free to use object.smth in modal template as usual property. And as soon as it will change you will see changes.

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)

How to specify which $scope a directive uses?

I have a directive that is watching something on $scope, and it is getting the wrong $scope.
so I have a state setup that specifies a controller:
.state('app.mystate', {
url: 'search/:searchText',
views: {
'mainPane#': {
templateUrl: 'views/content/search.html',
controller: 'ABCController'
}
},
resolve: {
searchPromise: ['$http', '$stateParams', function ($http, $stateParams) {
console.log($stateParams.searchText);
return $http.get(...blah...blah).then(blahblah);
}]
}
})
When this state gets activated, it goes to this view:
<ul ...>
<div ng-repeat="...">
<li ...>
<div ng-include="'views/widgets/somewidget.html'"></div>
</li>
</div>
</ul>
the ng-include loads this, which has a specific controller specified. And a directive.
<div ng-controller="XYZController">
<my-chart chart="chart" ...></my-chart>
</div>
Here is my directive:
angular.module('app.directive')
.directive('myChart', function () {
return {
template: '<div></div>',
scope: {
chart: '='
},
// wrong scope!
scope.$watch('chart', function (chart) { }
I figured that the <div> that contains the my-chart directive, that directive would get the $scope that goes into XYZController.
But the directive is getting the scope that is injected into ABCController, not XYZController as I want/expected. I can see XYZContoller getting activated.
How do I get the $scope that is injected into XYZController be the same scope that the my-chart directive sees?
The sample code for you directive seems to have been truncated/broken during copy/paste so it's hard to see where that scope.$watch call is at. If it is in the directive definition, after the return block, then it's never getting called but I would expect it to be in the controller.
Having said that, you can specify the controller to be used by the directive in the directive attributes which would seem appropriate here, unless you want to use the directive with different scopes..
<div>
<my-chart chart="chart"></my-chart>
</div>
angular.module('app.directive')
.directive('myChart', function () {
return {
controller: "XYZController",
bindToController: true
template: '<div></div>',
scope: {
chart: '='
}
})
.controller('XYZController', function($scope){
$scope.$watch('chart', function (chart) { });
});
scope: true will create a scope that is prototypically inerited from the parent scope, so you should be able to $watch a property on the parent scope.
angular.module('app.directive')
.directive('myChart', function () {
return {
template: '<div></div>',
scope: true,
link: function(scope){
scope.$watch('chart', function (chart) { });
});

Categories

Resources