javascript - How to provide an Api for your angular directive? -


until i've been developing widgets in javascript without angularjs. approach same: widget provide api allow clients change him part of application. approach has not change need use angularjs. have though in next solution , know options:

angular.module("app", ["mycustomwidget"])  .controller("mainctrl", ["$scope", "mycustomwidgetservice", function($scope, mycustomwidgetservice) {   $scope.mycustomwidgetservice = mycustomwidgetservice;   $scope.changemycustomwidget = function() {     $scope.mycustomwidgetservice.message = "this message written mainctrl";   } }]);   /** widget */ angular.module("mycustomwidget", [])  .factory("mycustomwidgetservice", function() {   var mycustomwidgetservice = {};   mycustomwidgetservice.message = "this default message inside service";   return mycustomwidgetservice; })  .directive("mycustomwidgetdirective", [function() {   return {     bindtocontroller: true,     controlleras: "$ctrl", // dont know used angular fails if not present -> https://docs.angularjs.org/error/$compile/noident     controller: "mycustomwidgetctrl",     scope: {},     template: '<button ng-click="changemycustomwidget()" type="button" name="button">click change directive</button><p>{{mycustomwidgetservice.message}}</p>'   } }])  .controller("mycustomwidgetctrl", ["$scope", "mycustomwidgetservice", function($scope, mycustomwidgetservice) {   $scope.mycustomwidgetservice = mycustomwidgetservice; //use service part of scope   $scope.changemycustomwidget = function() {     $scope.mycustomwidgetservice.message = "this message written mycustomwidgetctrl";   } }]); 

http://plnkr.co/edit/l58wpckgyyiongfoeewd

what think? idea use service part of directive controller?

you're supposed inject services controllers. entire purpose in life handle data controllers, middle managers of mvc app.

your use case 1 of common; you're having controller walk service , go, "hey, please show message me." later controller walks , asks service show different message. , on , forth.

you might have controller walk service -- possibly wearing trench coat , fedora -- and, hoarse whisper, go "hey, please hold data me. i've got friend coming pick up. no, it's cool , on level." , service, has had happen tryingly vast number of times in life, knows protocol doing it. put data on shelf; flip on light; resist urge alert(cops). later, controller -- wearing trench coat , fedora, time it's beige instead of black -- walks up, takes data, nods, disappears night.

in both cases, service knows nothing how or why it's doing anything; that's controller's job. similarly, controller doesn't know how or why done once hands off task; expects things work.

hopefully helps.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -