I've got a simple angular app, and I'm trying to inject some html into the page using ngBindHtml. However, it's not being injected. Here's my HTML:
<main id="main" ng-bind-html="oreGen | trust"></main>
And here's my angular app:
angular.module('programApp', ['programApp.controllers','programApp.filters','ngSanitize']);
angular.module('programApp.controllers', [])
.controller('programController', ['$scope', '$filter', function($scope, $filter){
$scope.oreGen = '<div class="oreFunction" ng-click="collectFunction(\'parenthesis\', 1)">test text</div>';
$scope.collectFunction = function(value1, value2){
alert(value1 + value2);
};
}]);
angular.module('programApp.filters', []).filter('trust', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
When the page is loaded, nothing appears inside the main element.
Here's a codepen: http://codepen.io/trueScript/pen/MwbVpO?editors=101
You can see the div being ngBinded does not appear. Why is this?
You can use a directive instead a filter. Please look at this JSFiddle
HTML:
<div ng-app="myApp" ng-controller="programController">
<dir id="main" content="oreGen"></dir>
</div>
JS:
angular.module('myApp', [])
.controller('programController', ['$scope', '$filter', function ($scope, $filter) {
$scope.oreGen = '<dir class="oreFunction" ng-click="collectFunction(\'parenthesis\', 1)">test text</dir>';
$scope.collectFunction = function (value1, value2) {
alert(value1 + value2);
};
}])
.directive('dir', function ($compile, $parse) {
return {
restrict: 'E',
link: function (scope, element, attr) {
scope.$watch(attr.content, function () {
element.html($parse(attr.content)(scope));
$compile(element.contents())(scope);
}, true);
}
}
});
Related
I have little problem with my angularJS directive, i want to display 2 photos in different way by using other html codes, but here comes a problem, that only one directive can works per page, the second one works only when i comment the previous one, there are no any errors in the browser console so i totally losing my mind trying to figure how to fix this problem.
ps displayed photos are taken form json file.
Angular:
(function(angular) {
'use strict';
angular.module('SinglePost', ['ngSanitize', 'ui.bootstrap'])
.controller('Controller', ['$scope', '$http', '$sce', '$location', function($scope, $http, $sce, $location) {
var weburl = document.URL;
var postId = weburl.substr(-2, 2)
$http.get(link + 'json=get_post&post_id=' + postId).then(function(response, date, content) {
$scope.content = response.data.post;
$scope.CategoryID = response.data.post.categories[0].id;
IDcategory = $scope.CategoryID
console.log(IDcategory)
$sce.trustAsHtml(content);
});
}])
.directive('myPost', function() {
return {
restrict: 'AEC',
scope: {
myPost: '='
},
templateUrl: '../common/directive/single-post.html'
};
});
})(window.angular);
(function(angular) {
'use strict';
angular.module('SinglePostsCategory', ['ngSanitize', 'ui.bootstrap'])
.controller('Controller', ['$scope', '$http', '$sce', '$location', function($scope, $http, $sce, $location) {
$http.get(link + 'json=get_category_posts&id=1').then(function(response, date, contents) {
$scope.myList = {
items: [
$scope.content = response.data.posts[0],
$scope.content = response.data.posts[0]
]
}
});
}])
.directive('myPost', function() {
return {
restrict: 'A',
scope: {
myPost: '='
},
templateUrl: '../common/directive/single-subpost_category.html'
};
});
})(window.angular);
HTML:
<div class="col-md-12">
<div ng-app="SinglePost">
<div ng-controller="Controller">
<div my-post="content">
<h1>CONTENT</h1></div>
</div>
</div>
<div class="row">
<div ng-app="SinglePostsCategory">
<div ng-controller="Controller">
<div ng-repeat="content in myList.items">
<div my-post="content">
<h1>CONTENT</h1></div>
</div>
</div>
</div>
</div>
</div>
any suggestion how to fix it? :)
function(angular) {
'use strict';
angular.module('SinglePost', ['ngSanitize', 'ui.bootstrap'])
.controller('SingleController', ['$scope', '$http', '$sce', '$location', function($scope, $http, $sce, $location) {
var weburl = document.URL;
var postId = weburl.substr(-2, 2)
$http.get(link + 'json=get_post&post_id=' + postId).then(function(response, date, content) {
$scope.content = response.data.post;
$scope.CategoryID = response.data.post.categories[0].id;
IDcategory = $scope.CategoryID
console.log(IDcategory)
$sce.trustAsHtml(content);
});
}])
.directive('mySinglePost', function() {
return {
restrict: 'AEC',
scope: {
myPost: '='
},
templateUrl: '../common/directive/single-post.html'
};
});})(window.angular);
angular.module('SinglePostsCategory', ['ngSanitize','ui.bootstrap'])
.controller('SinglePostsController', ['$scope', '$http', '$sce', '$location', function($scope, $http, $sce, $location) {
$http.get(link + 'json=get_category_posts&id=1').then(function(response, date, contents) {
$scope.myList = {
items: [
$scope.content = response.data.posts[0],
$scope.content = response.data.posts[0]
]
}
});
}])
.directive('mySinglePostsCategory', function() {
return {
restrict: 'AEC',
scope: {
myPost: '='
},
templateUrl:'../common/directive/singlesubpost_category.html'
};
});})(window.angular);
Rename your directive or your Controller name, Sometimes within the same page with two modules with the same controller name could cause the problem. I recommend to change both Controller names to be distinguishable.
For what I have seen I dont know why you need two module within one page . Can you combine it into one module and use two controllers?
HTML:
<div class="col-md-12">
<div ng-app="SinglePost">
<div ng-controller="SinglePostController">
<div my-single-post="content">
<h1>CONTENT</h1></div>
</div>
</div>
<div class="row">
<div ng-app="SinglePostsCategory">
<div ng-controller="SinglePostsController">
<div ng-repeat="content in myList.items">
<div my-single-posts-category="content">
<h1>CONTENT</h1></div>
</div>
</div>
</div>
</div>
You can not create same name directives even in the different module.
the module is used to divide the develop module,but it can't avoid polluting the namespace.if you want to use the module B in module A,you just need to inject module B like
angular.module('SinglePost', ['ngSanitize', 'ui.bootstrap','SinglePostsCategory'])
but make sure the directive and controller's name is different
var app = angular.module('jkuri.gallery', []);
app.controller("userProfile", ['$scope', '$http', '$location', '$resource', 'fullname', '$timeout', function($scope, $http, $location, $resource, fullname, $timeout){
$scope.openAlbum = function(){
$scope.showInject2 = true;
};
$scope.closeAlbum = function(){
$scope.showInject2 = false;
console.log("hover");
};
$scope.dataUri = function(){
//console.log('Res image', $scope.resImageDataURI);
//console.log($scope.resBlob);
console.log($scope.urlBlob);
//$scope.file = new File($scope.urlBlob, "name");
//console.log($scope.file);
$scope.loading = true;
$scope.cropOne = false;
$scope.sendRequest($scope.urlBlob, $scope.id, $scope.description, $scope.photoTag);
}
}]);
app.directive('ngGallery', ['$document', '$timeout', '$q', '$templateCache', '$location',function($document, $timeout, $q, $templateCache, $location) {
'use strict';
return {
restrict: 'EA',
scope: {
images: '=',
thumbsNum: '#',
sendRequest: '='
},
templateUrl: function(element, attrs) {
return attrs.templateUrl || defaults.templateUrl;
},
link: function (scope, element, attrs) {
setScopeValues(scope, attrs);
scope.images = [
{"id":"84","img":"images/image2.jpg","thumb":"images/image2.jpg"},
{"id":"85","img":"images/image2.jpg","thumb":"images/image2.jpg"},
{"id":"86","img":"images/image2.jpg","thumb":"images/image2.jpg"},
{"id":"87","img":"images/image2.jpg","thumb":"images/image2.jpg"},
{"id":"89","img":"images/image2.jpg","thumb":"images/image2.jpg"}
];
scope.sendRequest = function(imgBlob, id, imgDescription, imgTag){
console.log(imgBlob);
console.log(id);
console.log(imgDescription);
console.log(imgTag);
//scope.images.push({"id":id,"img":imgBlob,"thumb":imgBlob, "description":imgDescription});
scope.images.push({"id":"89","img":"images/image3.jpg","thumb":"images/image3.jpg"});
$timeout(function() {
var calculatedWidth = calculateThumbsWidth();
$thumbnails.css({ width: calculatedWidth.width + 'px' });
},100);
};
}
};
}]);
<div ng-app="jkuri.gallery" ng-controller="userProfile" class="cropppe">
<!-- <div class="cropped-one"><img ng-src="{{resImageDataURI}}" /></div> -->
<div class="cropped-one"><img ng-src="{{urlBlob}}"/></div>
<div class="float-right-btns">
<textarea name="" rows="" cols="" placeholder="Give a description"></textarea>
<a onclick='show();'>Cancel</a>
<a class="mfp-close" ng-click="dataUri()" style="background:#448ccb;color:#fff;">Upload</a>
</div>
</div>
<div ng-if="showInject2" style="position:absolute;" ng-gallery images="images" thumbs-num="11" send-request="sendRequest">
</div>
<div class="ng-gallery">
<div class="ng-scope">
<img class="ng-thumb" src="image1.jpg" ng-click="openAlbum()" ng-mouseover="closeAlbum()">
<div class="link-album"><p><strong>View</strong> or <strong>Add/Change</strong><br>Pictures</p></div>
</div>
I have a page in which directive is called when ng-if is true normally directive function is calling when i put directive in the page...and when ng-if gets true...after that function from controller is not calling function which is inside directive.
Exactly problem i am facing is that sendRequest function isn't calling from controller of directive and if i put that directive without ng-if it works like a charm...
Error: $scope.sendRequest is not a function
I have just simply added $parent in the function
<div ng-if="showInject2" style="position:absolute;" ng-gallery images="images" thumbs-num="11" send-request="$parent.sendRequest">
controller
angular.module('myApp')
.controller('myCtrl', [ '$mdDialog', '$mdMedia', 'viewDialog', myCtrl]);
..
function myCtrl( $mdDialog, $mdMedia, viewDialog) {
$scope.viewItem = function(ev,id) {
viewDialog.ITEM(ev,id)
};
}
html
<div ng-controller="myCtrl">
<md-list-item ng-repeat="item in myarr">
<a my-view-dialog">
<h4> {{item.id}} </h4>
</a>
</md-list-item>
</div>
When I call the function directly form controller the modal window works fine on click
using the directive
My directive
angular.module('myApp')
.directive('myViewDialog', function ($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('viewItem($event,item.id)')
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};;
});
Now I want to remove the controller dependency and directly call the viewDialog service from the directive it does not work.
here is code for service injection
angular.module('myApp')
.directive('myViewDialog', function ($parse, viewDialog) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('viewDialog.ITEM($event,item.id)')
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};;
});
Instead of
.directive('myViewDialog', function ($parse, viewDialog)
Try
.directive('myViewDialog', [ '$parse', 'viewDialog', function ($parse, viewDialog)
angular.module('myApp')
.directive('myViewDialog',['viewDialog','$parse', function (viewDialog,$parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('viewDialog.ITEM($event,item.id)')
return function (scope,elm,attr,ctrl){
elm.bind('click',function(){
exp(scope);
});
};
}
};;
}]);
I want to fire a directive based on demand using a service. Below is the directive code.
var app = angular.module('MyModule').service('DOMService', ['$rootScope', function ($rootScope) {
this.Manipulate = function () {
$rootScope.$emit('manipulateDOM');
};
}]).directive('domDirective', ['$rootScope', function ($rootScope) {
return {
restrict: 'EA',
replace: 'false',
scope: true,
link: function (scope, elm, attrs) {
$rootScope.$on("manipulateDOM", function () {
alert("Entered......");
// element.find('#DirectiveLable').css('background-color', 'red')
// element.find('#DirectiveLable').css('height', '100')
});
},
};
}]);
My HTML like below
<div id="example">
<div id="grid"></div>
<dom-directive>
<label id="DirectiveLable">Click Here</label>
</dom-directive>
</div>
I am calling the service like below inside my Angular Controller
angular.module('MyModule').controller('CitizenRelationAccordionController', ['$scope', '$q', '$attrs', 'DOMService',
function ($scope, $q, $attrs, DOMService) {
DOMService.Manipulate();
}
]);
Issue is that eventhough DOMService is firing, it's not invoking the directive method where alert has written
I think that you missed the [] in the module declaration: here is a working example from what you wrote.
Hope this could help,
Dario
I have a simple angular directive I would like to pass value to.
<div my-component binding-foo="foo">
<strong>get:</strong> {{isolatedBindingFoo}} // get it to output foo?
</div>
HTML
<div my-component binding='foo'> ... </div>
JS
yourApp.controller('yourController', ['$scope', function($scope) {
$scope.isolatedBindingFoo = '';
}])
.directive('myComponent', function() {
return {
controller: 'yourController',
scope: {
'binding': '=binding'
},
link: function($scope, $element, attrs) {
$scope.isolatedBindingFoo = attrs['binding'];
}
}
});
http://fdietz.github.io/recipes-with-angular-js/directives/passing-configuration-params-using-html-attributes.html
Cheers
AngularJS mangles HTML attributes to JS properties. eg, binding-foo in HTML will be mangled to bindingFoo in JS, and vice-versa
var myModule = angular.module('myModule', [])
.controller('yourController', ['$scope', function($scope) {
$scope.isolatedBindingFoo = '';
}])
.directive('myComponent', function() {
return {
restrict:'E,A',
controller: 'yourController',
scope: true,
link: function($scope, $element, attrs) {
$scope.isolatedBindingFoo = attrs['bindingFoo'];
}
}
});
http://jsfiddle.net/b2xo0o5u/3/
But in the example case this should be enough:
angular.module('myModule', [])
.directive('myComponent', function() {
return {
restrict:'EA',
scope: {
'isolatedBindingFoo': '#bindingFoo'
}
}
});
http://jsfiddle.net/b2xo0o5u/4/