angularjs: multiple binded functions in directive - javascript

I have a function in my directive that is bound to a function in my controller as follows:
HTML:
<div graph-visualization data="graphdata" type="graphtype" data-method="watchMonth" timespan="timespan" id="graph" ng-if="!loading">
</div>
Directive:
app.directive('graphVisualization', function() {
return {
restrict: 'A',
scope: {
data: '=',
type: '=',
timespan: '=',
monthFilter: '&method'
},
link: function(scope, element, attrs) {
scope.updateMonth = function() {
var func = scope.monthFilter();
func(scope.month)
}
scope.$watchGroup(['data', 'timespan', 'type'], function(newval, oldval) {
scope.month = 'something'
scope.updateMonth()
})
})
Controller:
$scope.watchMonth = function(value) {
//handle value passed from directive
}
As you can see I have a binded function 'watchMonth' in my controller which is called from the directive.
Now, I want to add another function in my directive which is binded to some other function in my controller. How do I go about it? Can't seem to get my head around it.
What I want is that I am handling a click in my directive and getting a value based on that click. Now, I want to pass this value to the controller which will modify 'graphdata'(on which I have supplied a watchgroup) in the controller.

In the html add the methods as shown:
month-filter="watchMonth()" second-function="function()"
Be sure to add parentheses at the end of the function name
<div graph-visualization data="graphdata" type="graphtype" month-filter="watchMonth()" second-function="secondFunction()" timespan="timespan" id="graph" ng-if="!loading">
app.directive('graphVisualization', function() {
return {
restrict: 'A',
scope: {
data: '=',
type: '=',
timespan: '=',
monthFilter: '&',
secondFunction: '&'
},
link: function(scope, element, attrs) {
scope.updateMonth = function() {
var func = scope.monthFilter();
func(scope.month)
}
scope.$watchGroup(['data', 'timespan', 'type'], function(newval, oldval) {
scope.month = 'something'
scope.updateMonth()
})
})
added a plunker, maybe that'll help
http://plnkr.co/edit/cISSlQpQF6lFQrDdbTg4?p=preview

Related

Angular call controller function from nested custom directive

I could use some help.
I have a controller containing a function called "loadInformation()". Inside this controller I use a service which is doing some DOM-Manipulation using custom directives.
These are the directives:
First custom Directive:
angular.module('...').directive('ngInputString', function () {
return {
restrict: 'AE',
replace: 'true',
scope: {
savedInformation: '=',
type: '#',
values: '='
},
templateUrl: 'directives/templates/inputString.html',
link: function (scope, element, attrs) {
scope.filterOb = {ttype: scope.type};
}
}
});
HTML file:
<div>
<input ttype="{{type}}" type="text" placeholder="{{param.name}}" value='{{param.value}}'
class='clean-input form-control'/>
<ng-saved-information type="STRING" saved-information="savedInformation"></ng-saved-information>
</div>
Nested custom directive:
angular.module('semtrosApp').directive('ngSavedInformation', function () {
return {
restrict: 'AE',
replace: 'true',
scope: {
savedInformation: '=',
type: '#'
},
template: '<ul><li ng-repeat="information in savedInformation | filter:filterOb">{{information.value}}<button type="button" ng-click="..?..">Use Information</button></li></ul>',
link: function (scope, elem, attrs) {
scope.filterOb = {ttype: scope.type};
}
}
});
When I dont use nested directives, it works just fine with that piece of code:
elem.bind('click', function() {
scope.$apply(function() {
scope.loadInformation();
});
});
But when they are nested, the second custom diretive is just looking inside the scope of the parent directive. Any idea how to pass through the function call?
It looks like the ngInputString directive already takes in some data and passes it down to ngSavedInformation. Why not have it take in a loadInformation callback as well and pass it down?
angular.module('...').directive('ngInputString', function () {
return {
scope: {
savedInformation: '=',
type: '#',
values: '=',
loadInformation: '&'
},
// etc
}
});
<ng-saved-information type="STRING" saved-information="savedInformation" load-information="loadInformation()"></ng-saved-information>
angular.module('semtrosApp').directive('ngSavedInformation', function () {
return {
scope: {
savedInformation: '=',
type: '#',
loadInformation: '&'
},
// etc
}
});
Also, instead of manually creating a click handler, you could do the following in the template:
ng-click="loadInformation()"

ng-click in angular directive - pass function from root scope

Fixed the issue, here is the final fiddle that shows it working:
http://jsfiddle.net/mbaranski/tfLeexdc/
I have a directive:
var StepFormDirective = function ($timeout, $sce, dataFactory, $rootScope) {
return {
replace: false,
restrict: 'AE',
scope: {
context: "=",
title: "="
},
template: '<h3>{{title}}</h3><form id="actionForm" class="step-form"></form><button ng-click="alert()" type="button">Save</button>',
link: function (scope, elem, attrs) {
}
}
}
How do I make the alert() do something from the controller?
Here is a fiddle:
http://jsfiddle.net/mbaranski/tfLeexdc/
Angular can be twitchy, so I've built a whole new fiddle to demonstrate all of the "glue-up" pieces you need to make this work.
First, you weren't passing the properties through to the directive, so I've made that adjustment:
// You have to pass the function in as an attribute
<hello-directive list="osList" func="myFunc()"></hello-directive>
Second, you were using onclick instead of ng-click in your template, which was part of the problem, so I made that switch:
// You need to use "ng-click" instead of "onclick"
template: '<h3>{{list}}</h3><button ng-click="func()" type="button">Button</button>',
And lastly, you need to bind the function in the scope of the directive, and then call it by the bound name:
scope: {
list: "=",
// Bind the function as a function to the attribute from the directive
func: "&"
},
Here's a Working Fiddle
All of this glued up together looks like this:
HTML
<div ng-controller="MyCtrl">
Hello, {{name}}!
<hello-directive list="osList" func="myFunc()"></hello-directive>
</div>
Javascript
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.name = 'Angular Directive';
$scope.osList = "Original value";
$scope.stuffFromController = {};
$scope.myFunc = function(){ alert("Function in controller");};
};
var HelloDirective = function() {
return {
scope: {
list: "=",
func: "&"
}, // use a new isolated scope
restrict: 'AE',
replace: false,
template: '<h3>{{list}}</h3><button ng-click="func()" type="button">Button</button>',
link: function(scope, elem, attrs) {
}
};
};
myApp.directive("helloDirective", HelloDirective);
If you'd like to execute a function defined somewhere else, make sure you pass it in by the scope directive attribute.
Here you can do:
scope: {
context: '=',
title: '=',
alert='&' // '&' is for functions
}
In the place where you using the directive, you'll pass the "expression" of the function (meaning not just the function, but the actual invocation of the function you want to happen when the click occurs.
<step-form-directive alert="alert()" title=".." context=".."></step-form-directive>

AngularJS - follow scope in custom directive

I have custom directive and want to send some parameters(objects) to this directive.
In directive I have select list based on one of this parameters and I need to follow this parameter.
My directive:
<custom-directive rows="users">
</custom-directive>
and template:
<ui-select ng-model="value">
<ui-select-match allow-clear="true">
{{$select.selected}}
</ui-select-match>
<ui-select-choices repeat="row in rows | filter: $select.search">
<div>
<span ng-bind-html="row | highlight: $select.search"></span>
</div>
</ui-select-choices>
</ui-select>
normally if rows change ui-select will automatically update select list. But if rows is variable from outside of this directive, it wont.
Can I have the same variable outside and inside directive?
I think I can use ng-model, but I'm not sure it is good solution.
EDIT:
My directive code:
.directive('custom-directive', function () {
return {
restrict: 'E',
replace: true,
scope: {
rows: '='
},
templateUrl: 'template.html',
controller: ['$scope', function($scope) {
console.log($scope);
}]
};
})
You can modify your custom directive to work with ng-model in the following way:
directive('customDirective', function() {
return {
// ...
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
// Write data to the model
// Call it when necessary
scope.setValue = function(value) {
ngModel.$setViewValue(value);
}
}
};
});
Initial state of ng-model value can be retrieved using that method:
ngModel.$render = function() {
var value = ngModel.$viewValue || [];
};
You can use link instead of the controller to handle functionality with rows. Setting rows : '=' should already take care of the two-way binding.
.directive('custom-directive', function () {
return {
restrict: 'E',
replace: true,
scope: {
rows: '='
},
templateUrl: 'template.html',
link: function(scope, element, attr) {
console.log(scope.rows);
};
};
})
EDIT:
Add a watch to the value that you need to do behavior on external change.
.directive('custom-directive', function () {
return {
restrict: 'E',
replace: true,
scope: {
rows: '='
},
templateUrl: 'template.html',
link: function(scope, element, attr) {
scope.$watch('rows', function(oldValue, newValue) {
console.log('This is the newValue : ' + newValue);
};
};
};
})

Passing Object to directive through attribute and containing variable

I wanna transfer a $scope.data to directive through its attribute in a Object, Can I achieve below format with any solution but not through separated attribute?
<custom-directive detail="{index:1, data: {{data}}}">
</custom-directive>
And the scope is set to below in directive
scope: {detail: "="}
One solution could be
return {
restrict: 'E',
require: 'ngModel',
scope: {
model: '=ngModel',
},
link: function(scope, element, attributes, ngModel) {
if (!ngModel) {
return;
}
console.log(scope.model); // your passed data
}
}
and then
<custom-directive ngModel="data"></custom-directive>
Now you will have your $scope.data passed to the directive inside scope.model. But note that, any change in scope.model in directive will reflect in $scope.data too.
To avoid that, you can simpley change ngModel.
return {
restrict: 'E',
scope: {
data: '=myData',
},
link: function(scope, element, attributes) {
console.log(scope.data); // your passed data
}
}
and then
<custom-directive my-data="data"></custom-directive>
You just write data only in your object, it will automatically resolves from your controller. Do as below:
HTML
<custom-directive detail="{index:1, data: data}">
</custom-directive>
Directive
myApp.directive('customDirective', function() {
return {
restrict:"AE",
scope:{
detail:"="
},
link:function(scope,ele,attrs) {
alert(JSON.stringify(scope.detail));
}
}
});
Fiddle Demo
You still have the solution to create your object in your controller :
$scope.detail = {index:1, data:$scope.data};
and to give it to your directive :
<custom-directive detail="detail"></custom-directive>

Angularjs directive

I want to have an attribute directive a bit similar to ng-model. I just want to additionally bind an input fields value to a scope variable (just in one direction input field -> scope variable). So I have just tried this directive but I can not get the directive called anyway.
script:
.directive('passivemodel', function () {
return {
restrict: "A",
scope: {
passivemodel: '='
},
link: function (scope, element, attrs) {
scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
console.log("passive model", newPassivemodel);
});
}
};
})
html:
<input data-passivemodel="keyword">
Edit:
Hmmm .. based on vilo20 answer I am running into a very strange behavior.
while this code is working very well:
<input data-ng-model="keyword" data-passivemodel="keyword">
this one does not (note the value of passivemodel):
<input data-ng-model="keyword" data-passivemodel="keyword2">. Sure I have defined the variable in the controller.
Controller:
.controller('SearchController', function($scope, $routeParams, $search) {
$scope.search = new $search();
$scope.keyword = "";
$scope.keyword2 = "";
})
Edit2: here is a fiddle http://jsfiddle.net/HB7LU/12107/
try this:
.directive('passivemodel', function () {
return {
restrict: "A",
scope: {
passivemodel: '='
},
link: function (scope, element, attrs) {
console.log("passive model", scope.passivemodel);
$scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
//put your logic when passivemodel changed
});
}
};
})
Hope it helps
Edit: Here is a plunker http://plnkr.co/edit/T039I02ai5rBbiTAHfzv?p=preview
Use the scope attribute:
.directive('passivemodel', function () {
return {
restrict: "A",
scope: {
"passivemodel": "="
},
link: function (scope, element, attrs) {
console.log("access passivemodel: ", scope.passivemodel);
}
};
})
Finally it was as simple as that:
.directive('modelRed', [function(){
return {
require: 'ngModel',
restrict: 'A',
scope: {},
link: function (scope, element, attrs, ngModel) {
scope.$watch(function () {
return ngModel.$modelValue;
}, function(newValue) {
scope.$parent[attrs.modelRed] = newValue;
//console.log(attrs.modelRed, newValue, scope);
});
}
}
}])
And in the html:
<p><input type="text" data-ng-model="testInput" data-model-red="redInput">{{redInput}}</p>
Of course you have to define testInput and redInput in the $scope object.

Categories