Angular directives, only one works per page - javascript

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

Related

i want to call function inside directive from controller where directive is included in html file which load when ng-if is true

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">

Unknown Provider when adding service to controller

I created a Modal service and when I injected the service into the controller, I am receiving an error that says "$Injector: unpr Unknown Provider". Here is my code below. Let me know if I am missing something.
This is the service I have so far.
'use strict';
angular.module('myApp.services', [])
.factory('modalService', ['$scope', function($scope) {
return {
openMenuModal: function(templateLink, windowAnimation) {
var modalInstance = $modal.open({
templateUrl: templateLink,
backdrop: 'static',
windowClass: windowAnimation,
controller: function($scope, $modalInstance) {
$scope.close = function() {
$modalInstance.close();
};
},
size: 'md',
scope: $scope,
keyboard: true
});
}
};
}]);
Here is the controller I have set up.
angular.module('myApp.controllers', ['ui.bootstrap', 'ngAnimate'])
.controller('HomeCtrl', function($scope, $http, $modal, modalService) {
$scope.opentheBook = modalService.openMenuModal('partials/Books.html', 'animated zoomIn');
});
Here is the template for the data in the modal - Books.html
<div ng-controller="HomeCtrl">
<div class="modalBox animated fadeIn">
<button class="btn btn-danger pull-right" type="button" ng-click="" tooltip="Close"><i class="fa fa-times"></i></button>
<h1>title</h1>
<p>description</p>
<div class="next">
<button class="btn btn-danger pull-right" type="button" tooltip="Close"><i class="fa fa-times"></i></button>
</div>
</div>
</div>
Here is the main home page where I am calling the openBook() to open the modal with the info from the json
<div class="Books">
<ul>
<li ng-repeat="book in thing.Books" class="list-unstyled"><a ng-click="opentheBook" href="#"><h6>{{book.name}}</h6></a></li>
</ul>
</div>
json for Books example --inside another array called things
"Books": [
{
"name": "Name of Book 1",
"description": "Description about book..."
},
{
"name": "Name of Book 2",
"description": "Description about book..."
}
]
This error results from the $injector being unable to resolve a required dependency. To fix this, make sure the dependency is defined and spelled correctly. For example, the following code will fail with the same error you received -$injector:unpr, if myService is not defined:
angular.module('myApp', [])
.controller('MyController', ['myService', function (myService) {
// Do something with myService
}]);
Making sure each dependency is defined will fix the problem, as noted below.
angular.module('myApp', [])
.service('myService', function () { /* ... */ })
.controller('MyController', ['myService', function (myService) {
// Do something with myService
}]);
So to answer your question, in your case you appear to be missing dependency
angular.module('myApp.controllers', ['ui.bootstrap', 'ngAnimate'])
.controller('HomeCtrl', function($scope, $http, $modal, modalService) {
$scope.opentheBook = modalService.openMenuModal('partials/Books.html', 'animated zoomIn');
});
To Inject modalService like so:
.controller('HomeCtrl', ['modalService', function($scope, $http, $modal, modalService) {
}]);
You also need to change up your factory module to angular.module('myApp.services', ['ui.bootstrap']) and use $uibModal since $modal is deprecated.
angular.module('myApp', ['ui.bootstrap'])
.factory('modalService', ['$uibModal', function($uibModal) {
return {
openMenuModal: function(templateLink, windowAnimation) {
var modalObj = $uibModal.open({
templateUrl: templateLink,
backdrop: 'static',
windowClass: windowAnimation,
controller: function($scope,$modalInstance){
$scope.ok = function(id){
//Process OK Button Click
$modalInstance.close();
},
$scope.cancel = function(){
$modalInstance.dismiss('cancel');
}
},
size: 'md',
keyboard: true,
resolve: {
someData: function () {
return 'Return some Data';
}
}
});
}
};
}])
.controller('HomeCtrl', ['$scope','modalService', function($scope, modalService, someData) {
$scope.dataFromService = someData;
$scope.opentheBook = function(){
modalService.openMenuModal('myModalContent.html', 'animated zoomIn');
};
}]);
UPDATE 1
As mentioned in the comments, do not attempt to inject $scope to your factory. Here is a Plunker I created which lets you open a modal by calling the factory.
http://plnkr.co/edit/G68NVYZlTqrIS0N2TKL4

ngBindHtml not Rendering Sanitized HTML

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);
}
}
});

Error when creating directive: TypeError: undefined is not a function

Hi, I am a angular newbie. I'm trying to declare a custom directive. But i'm getting the console error as follows.
Uncaught TypeError: undefined is not a function directives.js:5 (anonymous function)
See here : Link
app.js
'use strict';
var app = angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.widgets','myApp.directives']);
app.run(['$route', '$window', '$rootScope', function($route, $window, $rootScope) {
$route.when('/login', {template: 'partials/login.html', controller: loginCtrl});
$route.when('/home', {template: 'partials/home.html', controller: homeCtrl});
$route.otherwise({redirectTo: '/login'});
var self = this;
$rootScope.$on('$afterRouteChange', function(){
$window.scrollTo(0,0);
});
}]);
directives.js
angular.module('myApp.directives', [])
.directive('hello', function() {
return {
template : '<div style="position: relative"><img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" /><img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" /></div>'
}
};
});
You missed Lots of thing in your app, few are below.
Add ngRoute module inside dependency and angular-route.js file in reference.
You route configuration should be inside angular config block and It should use $routeProvider instead of only $route
Controller name inside $routeProvider.when should be wrap in single quote '
app.run will contain the $rootScope.$on event
And your directive contains extra closing curly brace }
App.js
'use strict';
angular.module('myApp.directives', []);
angular.module('myApp.filters', []);
angular.module('myApp.services', []);
angular.module('myApp.widgets', []);
var app = angular.module('myApp', ['ngRoute', 'myApp.filters', 'myApp.services', 'myApp.widgets', 'myApp.directives']);
app.config(['$routeProvider', '$window', '$rootScope', function($route, $window, $rootScope) {
$routeProvider
.when('/login', {
template: 'partials/login.html',
controller: 'loginCtrl'
})
.when('/home', {
template: 'partials/home.html',
controller: 'homeCtrl'
})
.otherwise({
redirectTo: '/login'
});
}]);
app.run(['$window', '$rootScope', function($window, $rootScope) {
$rootScope.$on('$afterRouteChange', function() {
$window.scrollTo(0, 0);
});
}]);
Directive.js
angular.module('myApp.directives')
.directive('hello', function() {
return {
template: '<div style="position: relative"><img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" /><img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" /></div>'
}
});
Hope this could help you, Thanks.
You've got one too many curly braces in your directive file:
angular.module('myApp.directives', [])
.directive('hello', function() {
return {
template : '<div style="position: relative"><img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" /><img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" /></div>'
};
});

Angular directive not working in ionic.js

I have some troubles to get my directive to load in my ionic.js web app using angular.
I can pass the variable {{someTitle}} from the controller to the template, however the directive does not get loaded, i.e. <div class="blaha" ng-transclude>abc123</div> does not get passed to the template... Am I missing something fatal below:
Ionic template:
<ion-view title="Roll the Dice">
<ion-content has-tabs="true">
<div my-dice>{{someTitle}}</div>
<div class="card">
<div class="item item-text-wrap">
{{someTitle}}
</div>
</div>
<button class="button button-dark button-full button-positive">
Full Width Block Button
</button>
</ion-content>
</ion-view>
Controller code:
'use strict';
angular.module('TrueDice.controllers', [])
// A simple controller that fetches a list of data from a service
.controller('HistoryIndexCtrl', function($scope, TrueRandomService) {
if($scope.rands="undefined"){
$scope.rands = [];
}
TrueRandomService.getRand(1).success(function(data){
$scope.rands.unshift(data);
console.log(data);
});
})
.controller('HistoryDetailCtrl', function($scope, $stateParams, TrueRandomService) {
//currently empty
}).controller('RollViewCtrl', function($scope){
$scope.someTitle="BLA";
}).directive('my-dice', ['$rootScope', function($rootScope) {
return {
restrict: 'E',
template: '<div class="blaha" ng-transclude>abc123</div>',
replace: true,
transclude: true,
scope: {},
controller: function($scope, $element) {
//currently empty
}
}
}]);
Remove - from directive name:
directive('myDice', ['$rootScope', function($rootScope) {
and according to restrict: 'E', you should place element in html:
<my-dice>{{someTitle}}</my-dice>
example

Categories