javascript - Pass variable from directive to controller -
i have directive definition , want pass currentscriptpath
testcontroller
.
how do that?
(function(currentscriptpath){ angular.module('app', []) .directive('test', function () { return { restrict: 'e', scope: {}, templateurl: currentscriptpath.replace('.js', '.html'), replace: true, controller: testcontroller, controlleras: 'vm', bindtocontroller: true }; }); })( (function () { var scripts = document.getelementsbytagname("script"); var currentscriptpath = scripts[scripts.length - 1].src; return currentscriptpath; })() ); testcontroller.$inject = ['$scope']; function testcontroller($scope) { // try access $scope.currentscriptpath here }
as want access currentscriptpath
in directive controller. need attach variable current scope inside link
function of directive & scope make currentscriptpath
available controller testcontroller
scope because have used bindtocontroller: true,
in directive.
markup
<div ng-controller="ctrl"> <test></test> </div>
directive
(function(currentscriptpath) { angular.module('app', []) .directive('test', function() { return { restrict: 'e', scope: {}, templateurl: currentscriptpath.replace('.js', '.html'), replace: true, controller: testcontroller, controlleras: 'vm', bindtocontroller: true, link: function(scope, element, attrs) { scope.currentscriptpath = currentscriptpath; //will update value of parent controller. } }; }); })( (function() { var scripts = document.getelementsbytagname("script"); var currentscriptpath = scripts[scripts.length - 1].src; return currentscriptpath; })() );
controller
function testcontroller($scope, $timeout) { var vm = this; $timeout(function() { alert($scope.currentscriptpath) //gets called after link function initialized }) }
Comments
Post a Comment