I'm a newbie at Angular, so don't be surprise if the answer to this question is pretty basic.
I'm trying to encapsulate a map in a directive, the map will have some custom behavior: I want it to communicate with a Service to retrieve all the points related to a merchant.
So I want to pass the merchant as a parameter to the directive:
This is the HTML:
<div ng-app="myApp">
<div ng-controller="Ctrl1">
<p>Ctrl 1: {{merchant1}}</p>
<map merchantDetails="{{merchant1}}"></map>
</div>
</div>
This is the javascript:
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl1', function ($scope) {
$scope.merchant1 = "foo"
});
myApp.controller('Ctrl2', function ($scope) {
$scope.merchant2 = "bar"
})
.directive('map', function () {
return {
restrict: 'E',
link: function (scope, element, attrs, controller) {
scope.merchant2 = attrs.merchantDetails;
},
scope: {
merchantDetails: "#"
},
template: 'Ctrl2: {{merchant2}}'
}
});
The problem is that scope.merchant2 at the template never gets updated.
I would like it to have "foo", or at worst "bar", not blank.
When I debug this in Chrome, controller Ctrl2 initialization is never executed. Why? I would expect it to be done before the link phase.
How do I do to get the "foo" value passed to Ctrl2?
The jsfiddle is available here.
You actually don't need the second controller.
I update the fiddler, please check if it's what you need:
https://jsfiddle.net/e7cfcakv/7/
<div ng-app="myApp">
<div ng-controller="Ctrl1">
<p>Ctrl 1: {{merchant1}}</p>
<map merchant-details="{{merchant1}}"></map>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl1', function ($scope) {
$scope.merchant1 = "foo"
});
myApp.directive('map', function () {
return {
restrict: 'E',
link: function (scope, element, attrs, controller) {
scope.merchant2 = scope.merchantDetails;
},
scope: {
merchantDetails: "#"
},
template: 'Ctrl2: {{merchant2}}'
}
});
You were almoust there
just change de directive attribute :
<map merchant-details="{{merchant1}}"></map>
Angular expects "-" before uppercase
Follow the angular js naming convention
just change the attribute "merchantDetails" to "merchant-details"
<map merchant-details="{{merchant1}}"></map>
Related
I'm consuming dynamically generated HTML from an API which may contain hyperlinks, and I'm wanting to replace the hrefs within them with ngClicks. The following directive appears to modify the HTML as intended when I check it in a DOM inspector, but clicking it does nothing. What am I doing wrong?
app.directive('replaceLinks', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function(scope) {
return scope.$eval(attrs.replaceLinks);
}, function(value) {
element.html(value);
angular.forEach(element.contents().find("a"), function(link) {
link.removeAttribute("href");
link.removeAttribute("target");
link.setAttribute("ng-click", "alert('test')");
});
$compile(element.contents())(scope);
});
}
};
}]);
Instead of removing the href please set it to blank (this will preserve the link css), also the ng-click calling the alert can be done by calling the alert('test') inside of a scope method, why the alert didn't fire, is explained in this SO Answer, please refer the below sample code!
// <body ng-app='myApp' binds to the app being created below.
var app = angular.module('myApp', []);
app.directive('replaceLinks', ['$compile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
angular.forEach(element.find("a"), function(link) {
link.setAttribute("href", "");
link.removeAttribute("target");
link.setAttribute("ng-click", "scopeAlert('test')");
});
$compile(element.contents())(scope);
}
};
}]);
// Register MyController object to this app
app.controller('MyController', ['$scope', MyController]);
// We define a simple controller constructor.
function MyController($scope) {
// On controller load, assign 'World' to the "name" model
// in <input type="text" ng-model="name"></input>
$scope.name = 'World';
$scope.scopeAlert = function(name) {
window.alert(name);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<div replace-links>
test 1
test 2
test 3
</div>
</div>
Hello i have my directive:
myApp.directive('hoverDirective',function($document){
return function(scope, element, attr){
scope:{value:'foo'};
element('mouseover',function(event){
console.log(event);
});
}
});
And I have it working:
<div hover-directive>
{{value}}
</div>
But now I want to hardcode data in directive, and get it by factory.
I read about scope:{value:'foo'}. But i have error while i was putting it inside of return function.
Can anyone help ?
UPDATE: I try putting code inside of return function no results.
Please see here : http://jsfiddle.net/qeCDL/
HTML:
<div ng-app="app">
<div ng-controller="firstCtrl">
<div hover-directive></div>
</div>
</div>
JS:
var app = angular.module('app', []);
app.directive('hoverDirective', function () {
return {
scope: {},
restrict: 'AE',
controller: function () {
},
template: '<h3>{{value}}</h3>',
link: function (scope, element, attrs) {
scope.value = "hove me";
element.on('mouseover', function (event) {
console.log(scope.value);
});
}
};
});
app.controller('firstCtrl', function ($scope) {
});
I have a directive that has a local scope where a partial contains ng-click.
The Fiddle is there: http://jsfiddle.net/stephanedeluca/QRZFs/13/
Unfortunatelly, since I moved my code to the directive, ng-click does not fire anymore.
The controller and the directive is as follows:
var app = angular.module('myApp', ['ngSanitize']);
app.directive('plantStages', function ($compile) {
return {
restrict: 'E',
transclude: true,
template: '<figure class="cornStages">\
<p ng-transclude style="color: skyblue"></p>\
<hr/>\
<p ng-bind-html="title"></p>\
<p ng-bind-html="subtitle">{{subtitle}}</p>\
<ul>\
<li ng-repeat="stage in stages" ng-click="changePage(stage)">{{stage}}</li>\
</ul>\
</figure>',
scope: {
stages:"=",
title:'#'
},
link: function (scope, element, attrs, ctrl, transclude) {
if (!attrs.title) scope.title = "Default title";
}
};
});
app.controller('myCtrl', function ($scope, $location, $http) {
$scope.stages = ['floraison', 'montaison'];
$scope.changePage = function (page) {
var url = "corn.page.html#/"+page;
console.log("Change page "+page+" with url "+url);
alert("about to change page as follows: document.location.href = "+url);
};
});
The html that invokes it is as follows:
<div ng-controller="myCtrl">
Stages,
<p ng-repeat="stage in stages">{{stage}}</p>
<hr/>
Plant stages
<plant-stages
title="<b>Exploration<br/>du cycle</b>"
subtitle="<em>This is a<br/>sub title</em>"
stages="stages"
>
Inner<br/>directive
</plant-stages>
</div>
Any idea?
You can't access changePage() defined in controller's scope from directive directly, since your directive has isolated scope. However, there are still several ways to do it:
Option 1:
Option 1 is the most simple option. However it is much like a workaround and I don't recommend to use it widely. You can get your controller's scope from element passed to link function and invoke changePage there:
link: function (scope, element, attrs, ctrl, transclude) {
if (!attrs.title) scope.title = "Default title";
scope.changePage = element.scope().changePage; // <= Get parent scope from element, it will have changePage()
}
Option 2:
If you don't have any logic that involves scope defined in the outer controller (as in your example), you can define inner controller for your directive and perform it there:
app.directive('plantStages', function ($compile) {
return {
...
controller: ['$scope', function($scope) {
$scope.changePage = function(page) {
var url = "corn.page.html#/"+page;
console.log("Change page "+page+" with url "+url);
alert("about to change page as follows: document.location.href = "+url);
}
}]
};
});
Option 3:
If you want do reuse logic defined in changePage() in different directives and controllers, the best way to do it is to move the logic to some service that may be injected to both controller and directive:
app.service('changePageService', function() {
this.changePage = function(page) {
var url = "corn.page.html#/"+page;
console.log("Change page "+page+" with url "+url);
alert("about to change page as follows: document.location.href = "+url);
}
});
app.controller('myCtrl', function ($scope, $location, $http, changePageService) {
...
changePageService.changePage('page');
...
});
app.directive('plantStages', function ($compile) {
...
controller: ['$scope', 'changePageService', function($scope, changePageService) {
$scope.changePage = changePageService.changePage;
}]
...
});
Option 4:
You can pass piece of code like changePage(page) as value of some attribute of the directive and inside directive define scope property with '&' that will create a function that will be executed in the outer controller's scope with arguments passed to that function. Example:
JavaScript
app.directive('plantStages', function ($compile) {
return {
restrict: 'E',
transclude: true,
template: '<figure class="cornStages">\
<p ng-transclude style="color: skyblue"></p>\
<hr/>\
<p ng-bind-html="title"></p>\
<p ng-bind-html="subtitle"></p>\
<ul>\
<li ng-repeat="stage in stages" ng-click="changePage({page: stage})">{{stage}}</li>\
</ul>\
</figure>',
scope: {
stages:"=",
title:'#',
changePage:'&'
},
link: function (scope, element, attrs, ctrl, transclude) {
if (!attrs.title) scope.title = "Default title";
}
};
});
HTML
<div ng-controller="myCtrl">
Stages,
<p ng-repeat="stage in stages">{{stage}}</p>
<hr/>
Plant stages
<plant-stages
title="<b>Exploration<br/>du cycle</b>"
subtitle="<em>This is a<br/>sub title</em>"
stages="stages"
change-page="changePage(page)"
>
Inner<br/>directive
</plant-stages>
Plunker: http://plnkr.co/edit/s4CFI3wxs0SOmZVhUkC4?p=preview
The idea of directives is to treat them as reusable components and avoid external dependencies wherever possible. If you have the possibility to define the behavior of your directive in its own controller then do it.
module.directive('myDirective', function () {
return {
restrict: 'E',
controller: function() { /* behaviour here */ },
template: '<div>Directive Template</div>',
scope: {
/* directive scope */
}
};
});
If this is not possible you can pass the function as explained in the linked question (see comment above). Check the updated fiddle.
I'm trying to use prettyprint plugin for my angularjs app.
But cannot make it works. I create a simple directive and call method prettyPrint(), but the code is not formatted.
FIDDLE: http://jsfiddle.net/Tropicalista/yAv4f/2/
App.directive('test', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).prettyPrint()
}
};
});
I modified your code and i'll update here:
http://jsfiddle.net/yAv4f/6/
html:
<div ng-app="Knob" ng-controller="myCtrl">
<pre class="prettyprint linemus"></pre>
<pre class="prettyprint linemus"><!DOCTYPE html><html lang="en"></html></pre>
</div>
javascript:
var App = angular.module('Knob', []);
App.controller('myCtrl', function($scope) {
$scope.dom = '<!DOCTYPE html><html lang="en"></html>'
})
App.directive('prettyprint', function() {
return {
restrict: 'C',
link: function postLink(scope, element, attrs) {
element.html(prettyPrintOne(scope.dom));
}
};
});
Basically, you need to use the file prettify.js to control the execution of the prettify() function, with prettyPrintOne() you can execute it in a specific html text.
And to simplify the use of the directive, like prettify stlyle, i'll suggest restric to 'C' a class and change the the directive name to 'prettyprint'
I've expanded on the previous answers and created a jsfiddle with a working directive that responds in realtime to model changes:
http://jsfiddle.net/smithkl42/cwrgLd0L/27/
HTML:
<div ng-app="prettifyTest" ng-controller="myCtrl">
<div>
<input type="text" ng-model="organization.message" />
</div>
<prettify target="organization"><pre><code class="prettyprint">console.log('{{target.message}}');
</code>
</pre>
</prettify>
</div>
JS:
var App = angular.module('prettifyTest', []);
App.controller('myCtrl', function ($scope) {
$scope.organization = {
message: 'Hello, world!'
};
});
App.directive('prettify', ['$compile', '$timeout', function ($compile, $timeout) {
return {
restrict: 'E',
scope: {
target: '='
},
link: function (scope, element, attrs) {
var template = element.html();
var templateFn = $compile(template);
var update = function(){
$timeout(function () {
var compiled = templateFn(scope).html();
var prettified = prettyPrintOne(compiled);
element.html(prettified);
}, 0);
}
scope.$watch('target', function () {
update();
}, true);
update();
}
};
}]);
h/t to #DanielSchaffer (see Template always compiles with old scope value in directive).
Angular already has this filter built-in for JSON:
<pre>
{{data | json}}
</pre>
If you want to make your own directive, you can use the JSON object directly:
app.filter('prettyJSON', function () {
function syntaxHighlight(json) {
return JSON ? JSON.stringify(json, null, ' ') : 'your browser doesnt support JSON so cant pretty print';
}
return syntaxHighlight;
});
With markup
<pre>
{{data | prettyJSON}}
</pre>
I would like to make a small addition to the directive by #carlosmantilla
You can achieve the same thing without creating the scope variable. I have added this correction on github
This should work properly I assume.
http://jsfiddle.net/yAv4f/143/
var App = angular.module('Knob', []);
App.controller('myCtrl', function($scope) {
$scope.text = "function f1(){int a;}";
})
function replaceText(str)
{
var str1 = String(str);
return str1.replace(/\n/g,"<br/>");
}
app.directive('prettyprint', function() {
return {
restrict: 'C',
link: function postLink(scope, element, attrs) {
element.html(prettyPrintOne(replaceText(element.html()),'',true));
}
};
});
I struggled with this issue for quite a while and wanted to chime in here, albeit much later than everyone else (for real though, who's still using AngularJS in late 2017? This guy.) My specific use-case was where I have code (xml) being dynamically loaded on the page which needed to be pretty printed over and over again.
This directive will take in your code as an attribute, remove the prettyprinted class that's added to the element right after you run prettyPrint(). It will watch for changes on the inputted code from the parent's scope and run the code again when changes occur.
Only dependency is that you have Google's code-prettify. I had it self-hosted, hence the PR.prettyPrint() (as instructed in the docs as of sept 2017).
The directive fully encapsulates the needed Google code-prettify functionality for dynamic content.
angular.module('acrSelect.portal.directives')
.directive('prettyPrint', ['$timeout', function($timeout) {
return {
restrict: 'E',
scope: {
'code': '=',
},
template: '<pre ng-class="{prettyprint: code}">{{ code }}</pre>',
link: function (scope, element, attr) {
scope.$watch('code',function(){
$timeout(function() {
//DOM has finished rendering
PR.prettyPrint();
element.find(".prettyprint").removeClass("prettyprinted");
});
});
}
}
}
]);
The html in the parent template might look
<pretty-print code="selectedCode" ng-show="codeIsSelected"></pretty-print>
Hope this helps another poor soul!
I have a example angularJS
<div ng-controller="testCtrl">
<test color1="color1" updateFn="updateFn()"></test>
</div>
<script>
angular.module('dr', [])
.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function() {
alert('123');
}
})
.directive('test', function() {
return {
restrict: 'E',
scope: {color1: '=',
updateFn: '&'},
template: "<button ng-click='updateFn()'>Click</button>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
</script>
</body>
</html>
I want when I click button, the alert box will appear, but nothing show.
Can anyone help me?
To call a controller function in parent scope from inside an isolate scope directive, use dash-separated attribute names in the HTML like the OP said.
Also if you want to send a parameter to your function, call the function by passing an object:
<test color1="color1" update-fn="updateFn(msg)"></test>
JS
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function(msg) {
alert(msg);
}
});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
color1: '=',
updateFn: '&'
},
// object is passed while making the call
template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
Click</button>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
Fiddle
Perhaps I am missing something, but although the other solutions do call the parent scope function there is no ability to pass arguments from directive code, this is because the update-fn is calling updateFn() with fixed parameters, in for example {msg: "Hello World"}. A slight change allows the directive to pass arguments, which I would think is far more useful.
<test color1="color1" update-fn="updateFn"></test>
Note the HTML is passing a function reference, i.e., without () brackets.
JS
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function(msg) {
alert(msg);
}
});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
color1: '=',
updateFn: '&'
},
// object is passed while making the call
template: "<button ng-click='callUpdate()'>
Click</button>",
replace: true,
link: function(scope, elm, attrs) {
scope.callUpdate = function() {
scope.updateFn()("Directive Args");
}
}
}
});
So in the above, the HTML is calling local scope callUpdate function, which then 'fetches' the updateFn from the parent scope and calls the returned function with parameters that the directive can generate.
http://jsfiddle.net/mygknek2/
In your 'test' directive Html tag, the attribute name of the function should not be camelCased, but dash-based.
so - instead of :
<test color1="color1" updateFn="updateFn()"></test>
write:
<test color1="color1" update-fn="updateFn()"></test>
This is angular's way to tell the difference between directive attributes (such as update-fn function) and functions.
How about passing the controller function with bidirectional binding? Then you can use it in the directive exactly the same way as in a regular template (I stripped irrelevant parts for simplicity):
<div ng-controller="testCtrl">
<!-- pass the function with no arguments -->
<test color1="color1" update-fn="updateFn"></test>
</div>
<script>
angular.module('dr', [])
.controller("testCtrl", function($scope) {
$scope.updateFn = function(msg) {
alert(msg);
}
})
.directive('test', function() {
return {
scope: {
updateFn: '=' // '=' bidirectional binding
},
template: "<button ng-click='updateFn(1337)'>Click</button>"
}
});
</script>
I landed at this question, because I tried the method above befire, but somehow it didn't work. Now it works perfectly.
use dash and lower case for attribute name ( like other answers said ) :
<test color1="color1" update-fn="updateFn()"></test>
And use "=" instead of "&" in directive scope:
scope: { updateFn: '='}
Then you can use updateFn like any other function:
<button ng-click='updateFn()'>Click</button>
There you go!
I had to use the "=" binding instead of "&" because that was not working.
Strange behavior.
#JorgeGRC Thanks for your answer. One thing though, the "maybe" part is very important. If you do have parameter(s), you must include it/them on your template as well and be sure to specify your locals e.g. updateFn({msg: "Directive Args"}.