Before setting the compiled html to dynamic-html div, my dynamicHtml is working correctly. As you can see, there's a onClick function in directive.
But unfortunately, after setting compiled html to div, onClick is not called anymore.
var content = $compile(res)($scope);
$('dynamic-html').html(content);
My dynamicHTML directive looks like this:
.directive('dynamicHtml', function($compile, $timeout) {
return {
restrict: 'E',
transclude: true,
link: function($scope, $element) {
$scope.datePickers = {};
$scope.onClick = function (variable, $event) {
var currentTarget = $event.currentTarget;
$scope.$parent.$parent.highlight(variable, true, currentTarget);
};
I tried to add transclude on directive as you can see. But it's not working on this case.
Can you please guide me to solve this problem?
Check it out the following code,
angular.module("myApp", [])
.directive("compiled", function($compile){
return {
restrict: "AE",
scope: {},
link: function(scope, ele, attrs){
var compiled = $compile("<div><hello-world></hello-world></div>")(scope);
ele.replaceWith(compiled);
}
}
})
.directive("helloWorld", function(){
return {
restrict: "AE",
scope: {},
transculde: true,
link: function(scope, ele, attrs){
scope.sayhello = function(){
alert("Hello World");
}
},
template: '<button ng-click="sayhello()">Say Hello</button>'
}
})
Html
<compiled></compiled>
Related
I am trying to dynamically load some HTML stored in a JSON file using Angular.
I am doing this by reading the JSON data into a scope and passing it to a directive that I wrote for loading HTML into the template.
Controller
.controller('testCtrl', function($scope, $http, $state){
$http.get('views/foo.json').then(function(res){
$scope.somehtml = res.data;
});
})
Directive
.directive('loadHtml', function($compile){
return {
restrict: 'AE',
scope: {
content: "#",
},
link: function(scope, element, attrs) {
scope.content = attrs.content;
element.html(scope.content).show();
$compile(element.contents())(scope);
},
template: '{{content}}'
};
})
This works!
<load-html content="hello success"></load-html>
This doesn't : (
<load-html content="{{somehtml}}"></load-html>
What am I missing here??
Found the solution myself, perhaps this helps someone:
I needed to "observe" the attribute value in the directive.
New Directive:
.directive('loadHtml', function($compile){
return {
restrict: 'AE',
scope: {},
link: function(scope, element, attrs) {
attrs.$observe('content', function(val) { /* $observing the attribute scope */
scope.content = val;
element.html(scope.content).show();
$compile(element.contents())(scope);
})
},
template: '{{content}}'
};
})
I need to call one function after directive render.
Actually i tried using $timeout function. But it's not working.
HTML Code:
<div ng-app='myApp' ng-controller='module-menu-controller'>
<layout-render></layout-render>
<div after-grid-render="getGridObject()"></div>
</div>
JS Code:
var app = angular.module("myApp", []);
app.controller("module-menu-controller", function($scope, $compile) {
$scope.getGridObject = function() {
alert("After render");
};
});
app.directive("layoutRender", function() {
return {
restrict : "E",
template : "<h1>Testing</h1>"
};
});
app.directive('afterGridRender', ['$timeout', function ($timeout) {
var def = {
restrict: 'A',
terminal: true,
transclude: false,
link: function (scope, element, attrs) {
$timeout(scope.$eval(attrs.getGridObject),0); //Calling a scoped method
}
};
return def;
}]);
JS Fiddle Link: https://jsfiddle.net/bagya1985/k64fyy22/1/
Here's a working fiddle.
Just have an additional attribute on the directive with the function:
HTML:
<div after-grid-render fnc="getGridObject()"></div>
Directive:
$timeout(scope.$eval(attrs.fnc),0);
Try this? Simple and clear
HTML
<div ng-app='myApp' ng-controller='module-menu-controller'>
<grid after-grid-render="getGridObject"></grid>
</div>
JS
var app = angular.module("myApp", []);
app.controller("module-menu-controller", function($scope) {
$scope.getGridObject = function() {
alert("After render");
};
});
app.directive("grid", function($timeout) {
return {
restrict : "E",
template : "<h1>Testing</h1>",
scope:{
afterGridRender:'='
},
link: function (scope, element, attrs) {
$timeout(scope.afterGridRender(),0); //Calling a scoped method
}
};
});
JSFiddle: https://jsfiddle.net/6o62kx3e/
Update
Do you mean you want it to be an attribute?
How about this one: https://jsfiddle.net/rt747rkk/
HTML
<div ng-app='myApp' ng-controller='module-menu-controller'>
<my-directive a='5' after-grid-render="getGridObject"></my-directive>
</div>
<script type="text/ng-template" id="myDirectiveTemplate.html">
<div> {{a}} {{b}} </div>
</script>
JS
var app = angular.module("myApp", []);
app.controller("module-menu-controller", function($scope) {
$scope.getGridObject = function() {
alert("After render");
};
});
app.directive('myDirective', function () {
return {
restrict: 'E',
replace: true,
templateUrl:"myDirectiveTemplate.html",
scope:{
a:'='
},
link: function (scope, element, attrs) {
scope.b=123;
scope.gridObject="my grid object here";
}
};
});
app.directive('afterGridRender', ['$timeout', function ($timeout) {
var def = {
restrict: 'A',
transclude: false,
link: function (scope, element, attrs) {
$timeout(function(){
scope.getGridObject();
alert(scope.$$childHead.gridObject);
});
}
};
return def;
}]);
I'm not really sure what you want to do.
If you want the attribute directive to access the scope of the element (as shown in the second alert box in the example), I don't think there's an elegant way. One way is to use scope.$$childHead, it works but variables prefixed with $$ are angular internal variables and we should not use them generally speaking.
I try to pass an attribute directive to an element directive, is it possible? I tried do it as in example but it doesn't work.
for example I have element directive:
<np-form-input
np-form-input-attrs="np-my-attr-directive"
>
</np-form-input>
JS:
.directive('npFormInput', [function () {
return{
restrict: 'E',
templateUrl: '/resources/view/common/form_input',
link: function(scope, element, attr){
scope.attributes= attr.npFormInputAttrs;
}
};
}])
And then in directive HTML
<input
{{attributes}}
>
Thanks in advance.
EDIT: My solution based on Micah Williamson answer:
.run(['$templateCache', '$http', function($templateCache, $http){
$http.get('/resources/view/common/form_input').success(function(data){
$templateCache.put('/resources/view/common/form_input', data);
});
}])
.directive('npFormInput', ['$templateCache', '$compile', function ($templateCache, $compile) {
return{
restrict: 'E',
compile: function (ele, attrs) {
var tpl = $templateCache.get('/resources/view/common/form_input');
tpl = tpl.replace('{{attributes}}', attrs.npFormInputAttrs);
var tplEle = angular.element(tpl);
ele.replaceWith(tplEle);
return function (scope, element, attr) {
$compile(tplEle)(scope);
};
},
};
}])
I've done something similar to what you're trying to do but I had to inject the attributes in the compile. You would need to add the template to $templateCache first though.
.directive('npFormInput', [function ($templateCache, $compile) {
return{
restrict: 'E',
compile: function(ele, attrs) {
var tpl = $templateCache.$get('/resources/view/common/form_input');
tpl = tpl.replace('{{attributes}}', attrs.npFormInputAttrs);
var tplEle = angular.element(tpl);
ele.replaceWith(tplEle);
return function(scope, element, attr){
$compile(tplEle)($scope);
};
}
};
}])
Html
<div class="result" ng-controller="test">
<div>{{result}}</div>
<a ng-href="{{result}}"></a>
</div>
JS
App.controller('AppCtrl', function AppCtrl($scope){
$scope.result = "www.google.com";
}
In a jquery file I can't modify because of some reason, some code changed the value of href, like:
$('.result>a').attr('href','www.youtube.com');
I want the value of $scope.result in the controller also changed from "www.google.com" to "www.youtube.com". But the result value in the div didn't change after the jquery code. Do I need write directive to watch the href attribute by myself? Or there are some other way to use ng-href? I try to write the directive by myself, but it didn't work. I hope you can give me a small example. Thanks :)
Update:
This is my directive, it didn't work, after something like $('.result>a').attr('href','www.youtube.com'), the console didn't print "change!" and the $scope.result didn't change:
APP.directive('result', function() {
return {
restrict: 'E',
scope: {
ngModel: '='
},
template: "<div class='result'><a ng-href='{{ngModel}}' href=''></a></div>",
replace: true,
require: 'ngModel',
link: function(scope, element, attrs) {
var $element = $(element.children()[0]);
scope.$watch($element.attr('href'), function(newValue) {
console.log("change!");
scope.ngModel = newValue;
})
}
};
});
Update Again: Still can't work...
Html:
<div class="result">
<a ng-href="{{result}}" ng-model="result" class="resulta"></a>
</div>
JS:
APP.directive('resulta', function() {
return {
restrict: 'C',
scope: {
ngModel: '='
},
link: function(scope, element, attrs) {
scope.$watch(attrs.href, function(newValue) {
console.log("change!");
scope.ngModel = newValue;
})
}
};
});
You can indeed create a custom directive to do it. See the example. I use transclude scope so you can put whatever you like in the link. I set 'replace: true' so the directive is removed and replaced with the <a>.
UPDATE
Using MutationObserver to watch for changes to the <a href>
var app = angular.module("MyApp", []);
app.directive("myHref", function() {
return {
restrict: 'E',
replace: true,
transclude: true,
link: function(scope, elem, attrs) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
scope.$parent.result = mutation.target.href;
scope.$apply();
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(elem[0], config);
},
scope: {
myHref: '='
},
template: '<a target="_blank" ng-transclude href="{{myHref}}"></a>'
};
});
app.controller('AppCtrl', function($scope) {
$scope.result = "http://www.yahoo.com";
$scope.$watch('result', function() {
alert($scope.result);
});
});
setTimeout(function() {
$('.result > a ').attr('href', 'http://www.youtube.com');
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp">
<div class="result" ng-controller="AppCtrl">
<my-href my-href="result">My Link</my-href>
</div>
</div>
Have the following problem. I want to make two directives. One of them will be an attribute for another.
Something like this.
<html>
<title>Directives</title>
<head lang="en">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js" type="text/javascript"></script>
<script src="main.js"></script>
</head>
<body ng-app="app">
<outer inner></outer>
</body>
</html>
The directive source code is here:
var app = angular.module('app', []);
app.directive('inner', function() {
return {
require: "^ngModel",
restrict: "AC",
transclude: true,
replace: false,
templateUrl: /* here is a path to template it's not interesting*/,
controller: function($scope) {
console.log('controller...');
},
link: function(scope, element, attrs) {
console.log('link...');
}
};
});
app.directive('outer', function($q, $rootScope) {
return {
require: "^ngModel",
restrict: "E",
replace: true,
scope: { /* isolated scope */ },
controller: function($scope) {},
templateUrl: /* path to template */,
link: function (scope, elem, attrs, ctrl) {}
}
});
The problem is that controller of outer works, but inner doesn't... Neither link nor controller function works... Can't understand what is wrong...
Any ideas?
The reason its not working is because both directives have been asked to render a template on the same element, and its ambiguous as to which one should be given priority.
You can fix this by giving the inner directive priority over the outer directive (higher numbers indicate higher priority).
Inner:
app.directive('inner', function() {
return {
priority:2,
restrict: "AC",
transclude: true,
replace: false,
template: "<div>{{say()}}<span ng-transclude/></div>",
controller: function($scope) {
$scope.message = "";
$scope.say = function() {
return "this is message";
};
// $scope.say(); // this doesn't work as well
console.log('controller...');
},
link: function(scope, element, attrs) {
// alert('hey');
// console.log('link...');
}
};
});
Also, both directives cannot transclude their contents. One must be 'transclude:false' and the other must be transclude:true.
app.directive('outer', function($q, $rootScope) {
return {
priority:1,
restrict: "E",
transclude:false,
scope: { /* isolated scope */ },
controller: function($scope) {
$scope.message = "";
$scope.sayAgain = function() {
return "one more message";
};
$scope.sayAgain(); // this doesn't work as well
},
template: "<div>{{sayAgain()}}</div>",
link: function (scope, elem, attrs, ctrl) {}
}
});
Here is a working fiddle:
JSFiddle