Custom Element Directives and attributes - javascript

myPage.html
<div ng-controller="MyPageCtrl">
<my-custom-directive arg1="{{currentObj.name}}"></my-custom-directive>
<div>
in myPageCtrl.js (Controller)
app.controller("MyPageCtrl", ["$scope", function ($scope) {
$scope.currentObj = {"name":"Collin"};
}]);
And this is how my directive code looks like
app.directive("myCustomDirective", [function () {
return {
restrict: "E",
controller: "MyCustomDirCtrl"
};
}]);
Finally here's my directive's controller,
app.controller("MyCustomDirCtrl", ["$attrs", function ($attrs) {
var arg = $attrs.arg1;
alert('Arg '+arg);
}]);
The alert just displays "{{currentObj.name}}" and not the value of the name property of currentObj.
Please can you suggest me ways to figure this out.
Thanks.

Not sure why did you use $attrs for a controller. Just use a normal $scope.
myPage.html
<div ng-controller="MyPageCtrl">
<my-custom-directive arg1="{{currentObj.name}}"></my-custom-directive>
<div>
myPageCtrl.js (Controller)
app.controller("MyPageCtrl", ["$scope", function ($scope) {
$scope.currentObj = {"name":"Collin"};
}]);
myCustomDirective
app.directive("myCustomDirective", [function () {
return {
restrict: "E",
controller: "MyCustomDirCtrl"
};
}]);
Directive's controller (change $attrs to $scope here),
app.controller("MyCustomDirCtrl", ["$scope", function ($scope) {
var arg = $scope.arg1;
alert('Arg '+arg);
}]);

Instead of accessing the attr from your controller, you could access it from your directive using the link function.
app.directive("myCustomDirective", [function () {
return {
restrict: "E",
controller: "MyCustomDirCtrl",
link: function(scope, element, attr) {
alert(attr.arg1);
}
};
}]);

Related

How to get controller scope from multi-level directives in AngularJS(without $parent)

How can I access controller scope from multi-level directives in below structure:
I create a directive that has multi-level scopes inside its.
1. Controller scope
1.2. Directive1 scope(main directive)
1.2.1. Directive2 scope
1.2.1.1 Directive3 scope
I want to get the controller scope from directive 3.
please don't refer to $parent because the parent level it's not certain and a user may use this directive inside another directive.(see below codes)
<div ng-controller="Test">
<custom-dir>
<dir1>
<dir2>
<dir3>
</dir3>
</dir2>
</dir1>
<custom-dir>
</div>
The users create a function in the Test controller and the function will be called in my Directive 3 scope(how to get controller scope?).
<div ng-controller="Test">
<dir1>
<dir2>
<dir3>
</dir3>
</dir2>
</dir1>
</div>
More details(please don't refer to syntax error):
The controller is:
App.controller('ScopeController', function ($scope, $rootScope, $uibModal, $http, $filter, $cookieStore, Common, $cookies) {
$scope.runTest = function () {
return `<input type='button' ng-click='testHtml()' value='Test'/>`;
}
$scope.testHtml = function () {
alert("work");
}
$scope.model=someModel;
$scope.config=someConfig;
$scope.columns={html: $scope.runTest};
});
the dir1 directive:
App.directive("dir1", function ($compile, $filter, $rootScope, $timeout, Common, $window, $http) {
return {
restrict: "E",
priority: 1,
terminal: false,
templateUrl: "Content/html/Table.html?version=2.6",
scope: {
model: "=",
columns: "=",
config: "=",
search: "#",
},
link: function (scope, elem, attrs) {
scope.CallFunc = function (html) {
if (typeof (html) =="function" )
return html();
else {
return scope.$parent.$eval(html + "()", {});
}
}
}
}
});
the dynamic directive compile the runTest output
App.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace:true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function (html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
If I change the line $compile(ele.contents())(scope); to $compile(ele.contents())(scope.$parent.$parent); it's work.
In this directive, I need get the controller scope without $parent because
some users may use this directive inside another directive same below:
<custom-dir>
<dir1 model="model" columns="columns" config="config">
<div dynamic="CallFunc(columns.html)"></div>
</dir1>
</custom-dir>
The using HTML tag
<dir1 model="model" columns="columns" config="config">
<div dynamic="CallFunc(columns.html)"></div>
</dir1>
This issue handle with following codes:
A service for storing the controller scope:
App.service('TableService', function () {
return {
MyScope: null
};
});
Inject the TableService to dynamic directive(this directive compiles dynamic content):
App.directive('dynamic', function ($compile,TableService) {
return {
restrict: 'A',
replace:true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function (html) {
ele.html(html);
$compile(ele.contents())(TableService.MyScope);
});
}
};
});
And finally in the controller:
App.controller('ScopeController', function ($scope, $rootScope, $uibModal,
$http, $filter, $cookieStore, Common, $cookies,TableService) {
TableService.myScope = $scope;
$scope.runTest = function () {
return `<input type='button' ng-click='testHtml()' value='Test'/>`;
}
$scope.testHtml = function () {
alert("work");
}
$scope.model=someModel;
$scope.config=someConfig;
$scope.columns={html: $scope.runTest};
});
After that, the dynamic directive can access controller scope and all dynamic events(like testHtml) will be called even if the directive put in another directive(without using the $parent).
thank you #shaunhusain, huan feng for giving me an idea.
In child controller do something like:
$scope.$broadcast('yourEvent');
In parent controller do the listener:
$scope.$on('yourEvent' , function(){
//Handle your logic
});
A special case service
.service('DirectDispatcher', function(){
return {
fireMe: angular.noop
}
});
First directive registers a function callback
.directive(
...
link:function(DirectDispatcher){
function myHandler() {window.alert('just testing')}
DirectDispatcher.fireMe = myHandler;
}
...
);
Second directive fires the function callback
.directive(
...
link:function(DirectDispatcher){
DirectDispatcher.fireMe();
}
...
);

Why won't $compile work with service using a directive?

Please have a look at this example, since it is the best way to explain the problem.
In this example if you click the directive link, it does not compile the template, but instead displays it as "{{1+1}}".
On the other hand if you click the "Simple link" it compiles the template and displays "2" instead.
angular.module('myApp', [])
.provider('$popup', function() {
var service = {};
this.$get = ['$compile', '$rootScope', function($compile, $rootScope) {
var template = $('<div>{{1+1}}</div>');
service.go = function() {
$(document.body).append(template);
$compile(template)($rootScope);
}
return service;
}];
})
.directive('popupLink', ['$popup', function($popup) {
return {
restrict: 'A',
scope: {},
link: function link(scope, element, attrs) {
element.click(function() {
$popup.go();
return false;
});
}
};
}])
.controller('mainCtrl', ['$scope', '$popup', function($scope, $popup) {
$scope.go = function() {
$popup.go();
};
}])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
<a ng-href="/test" popup-link>Directive link</a>
Simple link
</div>
My question is why isn't the template compiling with the directive? (but it does in the controller)
And how do I fix it so that it compiles in the directive also?
P.S. Here is the jsbin link in case you want to play around with the code:
http://jsbin.com/vuzutipedu/edit?html,js,output
The directive needs to do scope.$apply():
link: function link(scope, element, attrs) {
element.click(function() {
$popup.go();
//ADD apply
scope.$apply();
return false;
});
The click event handler executes outside the AngularJS framework. A framework digest cycle needs to be performed to execute the watcher for the {{1+1}} interpolation.
It works with the ng-click directive because that directive includes scope.$apply.
For more information, see
AngularJS Developer Guide - Integration with the browser event loop
DEMO
angular.module('myApp', [])
.provider('$popup', function() {
var service = {};
this.$get = ['$compile', '$rootScope', function($compile, $rootScope) {
var template = $('<div>{{1+1}}</div>');
service.go = function() {
$(document.body).append(template);
$compile(template)($rootScope);
}
return service;
}];
})
.directive('popupLink', ['$popup', function($popup) {
return {
restrict: 'A',
scope: {},
link: function link(scope, element, attrs) {
element.click(function() {
$popup.go();
//ADD apply
scope.$apply();
return false;
});
}
};
}])
.controller('mainCtrl', ['$scope', '$popup', function($scope, $popup) {
$scope.go = function() {
$popup.go();
};
}])
<script src="//unpkg.com/jquery"></script>
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
<a ng-href="/test" popup-link>Directive link</a>
Simple link
</div>
Try this in $get, instead of $compile(template)($rootScope)
$compile(angular.element(template))(angular.element(template).scope());
Let me know if it works

Defining my own 'require' on a directive, but throw error - AngularJs

Let us say I have this html:
<div ng-controller="MyCtrl">
<br>
<my-directive my-name="name">Hello, {{name}}!</my-directive>
</div>
with this simple controller:
myApp.controller('MyCtrl', function ($scope) {
$scope.name = 'Superhero';
});
And I have a directive in which I want to change the 'name' using require like this:
myApp.directive('myDirective', function($timeout) {
var controller = ['$scope', function ($scope) {
$scope.name = "Steve";
}];
return {
restrict: 'EA',
require: 'myName',
controller: controller,
link: function(scope, element, attrs, TheCtrl) {
TheCtrl.$render = function() {
$timeout(function() {
TheCtrl.$setViewValue('StackOverflow');
}, 2000);
};
}
};
});
But throws:
Error: No controller: myName
Here is the fiddle
But if I implement it using ng-model, works. Look here in this other fiddle
I have read that if you use 'require' in a directive, you need to have a controller for it.
So:
What I'm doing is wrong? It is not in this way? I need to do any other thing?
Well finally I got it.
Essencially what I'm trying to do is something called: 'Communication between directives using controllers'. I have found an article explaining this, and helped me a lot:
The view:
<div ng-controller="MyCtrl">
<br>
<my-directive my-name>Hello, {{name}}!</my-directive>
</div>
As you see above, there are two directives: my-directive and my-name. I will call inside my-directive a function from the controller of my-name directive using require.
myDirective:
myApp.directive('myDirective', function($timeout) {
return {
require: 'myName',
link: function(scope, element, attrs, myNameCtrl) {
$timeout(function() {
myNameCtrl.setName("Steve");
}, 9000);
} // End of link
}; // return
});
myName:
myApp.directive('myName', function($timeout) {
var controller = ['$scope', function ($scope) {
// As I tried, this function can be only accessed from 'link' inside this directive
$scope.setName = function(name) {
$scope.name = name;
console.log("Inside $scope.setName defined in the directive myName");
};
// As I tried, this function can accessed from inside/outside of this directive
this.setName = function(name) {
$scope.name = name;
console.log("Inside this.setName defined in the directive myName");
};
}];
return {
controller: controller,
link: function(scope, element, attrs, localCtrl) {
$timeout(function() {
localCtrl.setName("Charles");
}, 3000);
$timeout(function() {
scope.setName("David");
}, 6000);
} // End of link function
};
});
Interesting and works like a charm. Here is the fiddle if you want to try it out.
Also, you can get communication between directives using events. Read this answer here on SO.

Pass a value from parent directive template to child directive

Problem:
I'm attempting to pass a value from an ng-repeat into a child-directive but when I try to access my passed variable in directive 2 I get "undefined".
Here's an illustration of what I am attempting. Basically directive 1 represents an array of widgets while directive 2 represents a single widget. I am attempting to pass an item from the ng-repeat loop into my child directive.
My Attempt:
Here's a simplified version of my directive 1 template:
<li ng-repeat="item in widgets">
<directive2 item="item"></directive2>
</li>
Here's a simplified version of directive 2:
angular.module('directive2').directive(
['$compile', '$rootScope',
function ($compile, $rootScope) {
return {
restrict: 'E',
scope: { item: '=' },
templateUrl: 'ext-modules/tile/widgetTemplate.html',
link: function (scope, element, attrs) {
console.log(scope.item); // undefined
}
};
}]);
The ng-repeat on widgets creates two items and I have verified that the data exists. The application works fine and doesn't throw an error but my console.log returns : undefined.
My Question:
How can I pass a value from a directive template's ng-repeat into a child-directive?
here's a fiddle: http://jsfiddle.net/3znEu/112/
Yet another solution proposal:
HTML:
<div ng-controller="MyCtrl">
<directive1></directive1>
</div>
JavaScript:
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.widgets = [
'a', 'b', 'c', 'd'
];
}])
.directive('directive1', function () {
return {
restrict: 'E',
scope: false,
template:
'<li ng-repeat="item in widgets">' +
'<directive2 item="item"></directive2>' +
'</li>'
}
})
.directive('directive2', ['$compile', '$rootScope',
function ($compile, $rootScope) {
return {
restrict: 'E',
scope: { item: '=' },
template:
'<div>elem = {{item}}</div>',
link: function (scope, element, attrs) {
console.log(scope.item);
}
}
}]);
Fiddle: http://jsfiddle.net/masa671/dfn75sp3/
It works fine when you put directive2 as directive name, not module:
http://jsfiddle.net/3znEu/113/
'use strict';
var app = angular.module('myApp', [])
.controller('myController', ['$scope', function($scope) {
$scope.greeting = 'Hello World!';
$scope.widgets = ["111","222","333"]
}]);
app.directive('directive1',
['$compile', '$rootScope',
function ($compile, $rootScope) {
return {
restrict: 'E',
scope: { item: '=' },
template: '<div>{{item}}</div>',
link: function (scope, element, attrs) {
console.log(scope.item); // undefined
}
};
}]);
I have modified your fiddler a bit http://jsfiddle.net/3znEu/115/. Few changes
1. Added a restrict to your directive.
2. Added a template to render the Items (only for testing and demo)
3. Changed items in scope from '#' to '='
angular.module("myApp").directive("directive1", function(){
return {
restrict: 'E',
scope: {
item: "="
},
template: "{{item}}"
}
});

AngularJS: Access directive from controller

Background
I have a top level directive which needs to be accessed by a controller. Please consider this Plunk.
Directive
app.directive('topDirective', ['$compile', function($scope){
return {
scope: {},
restrict: 'E',
template: '<h3>Top Directive</h3><p><button ng-click="CallMe()">Click Me</button></p>',
controller: function($scope) {
var self = {};
$scope.CallMe = function(){
alert('Call Me');
};
},
link: function($scope, $elem, $attrs, $ctrl) {
}
};
}]);
Controller that needs access
app.controller('subController', [
'$scope',
function($scope){
var self = {};
$scope.CallDirective = function() {
alert('>>> Replace by call to directive function CallMe (somehow) <<<')
};
}]);
Question
What do I need to do to replace this line:
alert('>>> Replace by call to directive function CallMe (somehow) <<<')
by an actual call to the CallMe() function in the directive?
If not possible directly, is there a way to share functionally that both the directive and controller can use? My first thought would be a service, but it would need to do DOM manipulation in the real scenario, so that's not an option.
Any suggestions?
in Controller emit the event
app.controller('subController', [
'$scope','$rootScope',
function($scope,$rootScope){
var self = {};
$scope.CallDirective = function() {
var data ='This is new data';
$rootScope.$emit('callDirective',data);
};
}]);
and in directive you can do it like
app.directive('topDirective', ['$compile', function($scope){
return {
scope: {},
restrict: 'E',
template: '<h3>Top Directive</h3><p><button ng-click="CallMe()">Click Me</button></p>',
controller: function($scope,$rootScope) {
var self = {};
$scope.CallMe = function(data){
alert(data);
};
$rootScope.$on('callDirective',function(type,data){
$scope.CallMe(data);
});
},
link: function($scope, $elem, $attrs, $ctrl) {
}
};
}]);

Categories

Resources