Saturday 15 May 2010

AngularJS: Calling a Method in a Controller from a Directive, and Passing Parameters -



AngularJS: Calling a Method in a Controller from a Directive, and Passing Parameters -

i’m new angularjs, , have app (v 1.2.26) contains directive handle reading files when user selects them via html file input. directive calls service parses files, , needs update view tabular info parsed files. of working except updating view.

in order update view, have controller method phone call directive.

the first question: way update view info directive (i.e. passing info controller)?

second question (assuming valid approach): calling method in controller using next code doesn’t work. doing wrong?

the app module:

var app = angular.module('myapp', []);

the controller (in same file app module):

app.controller('myctrl', function($scope) { this.updatepanel = function(mydata) { // never gets called: console.log('you rang?'); }; });

the file-handling directive (in different file):

angular.module('myapp') .directive('filebrowser', ['mydataservice', function (mydataservice) { homecoming { restrict: 'ea', require: 'ngmodel', replace: true, template: '<div><div><input type="file" class="btn btn-default"/></div></div>', link: function (scope, element, attrs, ngmodel) { var container = element.children(); var bindfilecontrolchange = function () { // [snip] read file (this works) //... // pass file mydataservice (this works): var mydata = mydataservice.parse(myfilecontent); // phone call controller method - doesn't work: scope.$apply('updatepanel(mydata)'); //... }; } }; } ]);

thanks insights!

the first question: it's not wrong. if can utilize directive's controller, might sense more comfortable maintaining mill includes tabulated data. know used link when made file browser directive, suspect not alternative (but i'm not certain).

second question: using example, think want pass in function. this, recommend using isolated scope variable, example:

angular.module('myapp').directive('filebrowser', ['mydataservice', function (mydataservice) { homecoming { // ... scope: { updatepanel: "=" }, // ... link: function (scope, element, attrs, ngmodel) { // ... scope.updatepanel(mydata); // phone call whenever // ... } }; });

and html:

<div ng-controller="myctrl"> <file-browser update-panel="updatepanel"></file-browser> </div>

let me know if suits needs. if not, i'll seek come improve answer.

angularjs-directive

No comments:

Post a Comment