Dynamically added element id is null - javascript

I'm new to angularJS. When I click a button it will show a dialog, the dialog's html code is:
<img id="imgId" ng-src="{{imgSrc}}">
In controller, when I try to access imgId using JavaScript it showing null. Same with the JQuery.
console.log(document.getElementById('imgId')); // null
Here is my code:
angular.module('BlankApp', ['ngMaterial']).
controller('mainController', function($scope, $mdDialog) {
$scope.showCustomDialog = function(ev) {
$mdDialog.show({
controller: DialogController,
template: '{{hello}}<img id="imgId" ng-src="{{imgSrc}}">',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
});
function DialogController($scope, $timeout) {
$scope.hello = "Hello World";
$scope.imgSrc = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcScku8D7qo2hWD-eqb_WKTVjMjjiJFLo7uDQQ4RZWRNw9TJ-j7nYg";
$timeout(function() {
console.log(document.getElementById('imgId'));
console.log(angular.element(document.getElementById('imgId')));
});
}
}
});
<html lang="en">
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
</head>
<body ng-app="BlankApp" ng-controller="mainController" ng-cloak>
<md-button ng-click="showCustomDialog($event)" class="md-primary">Show Dialog</md-button>
<!-- Angular Material requires Angular.js Libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
</body>
</html>
(plunker)

You need to give the dialog a chance to render, before you can get a reference to it.
Wrap the getElementById calls in a $timeout:
$timeout(function(){
console.log(document.getElementById('imgId'));
console.log(angular.element(document.getElementById('imgId')));
});
Keep in mind that you need to include the $timeout in your controller:
function DialogController($scope, $timeout) {
Here's a working example using your plunker's code:
angular.module('BlankApp', ['ngMaterial']).
controller('mainController', function($scope, $mdDialog) {
$scope.showCustomDialog = function(ev) {
$mdDialog.show({
controller: DialogController,
template: '{{hello}}<img id="imgId" ng-src="{{imgSrc}}">',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
});
function DialogController($scope, $timeout) {
$scope.hello = "Hello World";
$scope.imgSrc = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcScku8D7qo2hWD-eqb_WKTVjMjjiJFLo7uDQQ4RZWRNw9TJ-j7nYg";
$timeout(function() {
console.log(document.getElementById('imgId'));
console.log(angular.element(document.getElementById('imgId')));
});
}
}
});
<html lang="en">
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
</head>
<body ng-app="BlankApp" ng-controller="mainController" ng-cloak>
<md-button ng-click="showCustomDialog($event)" class="md-primary">Show Dialog</md-button>
<!-- Angular Material requires Angular.js Libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
</body>
</html>

Related

How to use Multiple buttons with different controller in angularjs for redirecting

I wrote the program that is having 3 buttons and if i click on the particular button it should redirect to corresponding page mentioned in app.js
my requirement is each button should have a controller and it should redirect properly and it should show a console message that which button is clicked
i'm sharing my code but it is not working
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<link data-require="bootstrap-css" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<!-- Le javascript
================================================== -->
<script data-require="jquery" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.min.js"></script>
<script>var myItemsApp = angular.module('myItemsApp', ['ngRoute']);</script>
</head>
<body ng-app="myItemsApp">
<div>
<h3>Test</h3>
<div class="row">
<div class="col-md-4">
<button href="/test1" ng-click="submit1()">Button1</button>
<button href="/test2" ng-click="submit2()">Button2</button>
<button href="/test3" ng-click="submit3()">Button3</button>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
<script src="testcntrl.js"></script>
</html>
#app.js
myItemsApp.config(['$routeProvider',function($routeProvider) {
$routeProvider
.when('/test1', {
templateUrl : 'test.html',
controller : 'button1Controller'
})
.when('/test2', {
templateUrl : 'test1.html',
controller : 'button2Controller'
})
.when('/test3', {
templateUrl : 'test2.html',
controller : 'button3Controller'
})
.otherwise({
redirectTo: '/'
});
}]);
testcntrl.js
myItemsApp.controller('button1Controller', ['$scope','$location', function($scope,location){
$scope.submit1 = function() {
console.log("I clicked on submit button1Controller");
location.path('/test1');
}
}]);
myItemsApp.controller('button2Controller', ['$scope','$location', function($scope,location){
$scope.submit2 = function() {
console.log("I clicked on submit button2Controller ");
location.path('/test2');
}
}]);
myItemsApp.controller('button3Controller', ['$scope','$location', function($scope,location){
$scope.submit3 = function() {
console.log("I clicked on submit button3Controller");
location.path('/test3');
}
}]);
test1.html
<h1>hello</h1>
You should add ng-view to render template. and add # to url in the href.
also you don't need ng-click when time using <a> tag.and you injected service into controller incorrectly. you should inject $location instead of location
if you want to remove # from url so enable html mode.
<div class="col-md-4">
<a href="#/test1" >Button1</a>
<a href="#/test2" >Button2</a>
<a href="#/test3" >Button3</a>
</div>
<div ng-view=""></div>
</div>
Demo
Your idea is ok, it should work but:
No need href in button.
Instead of button you can simply use anchor with #/test1 #/test2
If you still want this way you need another controller "main controller"
This can work:
// Code goes here
var myItemsApp = angular.module('myItemsApp', ['ngRoute']);
myItemsApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/test1', {
templateUrl: 'test1.html',
controller: 'button1Controller'
})
.when('/test2', {
templateUrl: 'test2.html',
controller: 'button2Controller'
})
.when('/test3', {
templateUrl: 'test3.html',
controller: 'button3Controller'
})
.otherwise({
redirectTo: '/'
});
}]);
myItemsApp.controller('initialController', ['$scope', '$location', function($scope, location) {
$scope.submit1 = function() {
console.log("I clicked on submit button1Controller");
location.path('/test1');
}
$scope.submit2 = function() {
console.log("I clicked on submit button2Controller ");
location.path('/test2');
}
$scope.submit3 = function() {
console.log("I clicked on submit button3Controller");
location.path('/test3');
}
}]);
myItemsApp.controller('button1Controller', ['$scope', '$location', function($scope, location) {
}]);
myItemsApp.controller('button2Controller', ['$scope', '$location', function($scope, location) {
}]);
myItemsApp.controller('button3Controller', ['$scope', '$location', function($scope, location) {
}]);
Plunker demo

Use a different angular controller for bootstrap modal

I'm calling for the bootstrap modal HTML file from my main HTML file here is an example code of what I'm doing. Link
<div class="container" ng-controller="MainAngularControler"> <!--The main div with the controller in it-->
As it shows can anyone suggest a way to call another Angular controller for bootstrap modal. because the button that calls for the modal to load is in a div which already has an angular controller, this doesn't let the modal to load another different angular controller. The idea behind all these is to make my code more understandable.
When creating the modal instance in your angular controller you need to pass the modal controller like this.
var modalInstance = $uibModal.open({
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'myModalContent.html',
size: "lg",
controller: 'modalController'
});
Have a look at this plunker or the code below.
var app = angular.module('plunker', ["ui.bootstrap"]);
app.controller('MainCtrl', function($scope, $uibModal) {
$scope.name = 'World';
$scope.OpenModal = function(){
var modalInstance = $uibModal.open({
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'myModalContent.html',
size: "lg",
controller: 'modalController'
});
modalInstance.result.then(function (selectedItem) {
//$ctrl.selected = selectedItem;
}, function () {
//$log.info('Modal dismissed at: ' + new Date());
});
};
});
app.controller('modalController', function($scope){
$scope.text = 'I am from modal controller SCOPE';
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body" id="modal-body">
THIS IS A MODAL. {{text}}
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="$ctrl.ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.cancel()">Cancel</button>
</div>
</script>
<a ng-click="OpenModal()">Open Modal</a>
</body>
</html>

angularjs:-Uncaught Error: [$injector:modulerr] issue while running code

Hi I was trying to implement a pop up in angular but while doing so I am getting the error Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.9/$injector/modulerr?p0=PopupDemo&p1=Error%…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.9%2Fangular.min.js%3A19%3A463)
The below is the code I have written.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body ng-app="PopupDemo">
<div ng-controller="PopupDemoController">
<a ng-click="open()">Open Popup</a>
</div>
<script>
angular.module('PopupDemo', ['ui.bootstrap']);
angular.module('PopupDemo')
.controller('PopupDemoController',['$scope','$modal',function ($scope, $modal) {
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'first.html',
});
}
}]);
</script>
</body>
I am not sure why I am getting the error and what is the way out..Not getting any sort of help from online resources and angular website..
I do know there is some module which is missing in the file,But not sure how to check for it.
Can someone please help me out..Am getting stuck in this.
Thanks a lot guys
Following code should probably work.
Have added bootstrap.ui js
Changed the Module name accordingly
Code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.2.1/ui-bootstrap.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body ng-app="PopupDemo">
<div ng-controller="PopupDemoController">
<a ng-click="open()">Open Popup</a>
</div>
<script>
var myMod = angular.module('PopupDemo', ['ui.bootstrap']);
myMod.controller('PopupDemoController', ['$scope', '$uibModal', function($scope, $modal) {
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'first.html',
});
}
}]);
</script>
</body>
Try to replace with this code
<script>
var app = angular.module('PopupDemo', ['ui.bootstrap']);
app.controller('PopupDemoController', ['$scope', '$modal', function($scope, $modal) {
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'first.html',
});
}
}]);
</script>
you didnt load the ui.bootstrap module
you can use this cdn
It seems that you also need to add angular bootsrap-ui reference:
For example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.2.1/ui-bootstrap.js"></script>
Update:
You are missing ui.bootstrap.js file. please include that. It is not suffice to include bootstrap.js.
Also, please use $uibModal instead of $modal
myApp.controller('myController', ['$scope', '$uibModal', function($scope, $uibModal) {
$scope.hi = "hello world";
$scope.open = function() {
var modalInstance = $uibModal.open({
template: '<h1>Hello world</h1>',
});
}
}]);
JQuery js should come before bootstrap js. Could you please try that

AngularJS dynamically load template and js file

I want to dynamically add menu JavaScript file and html to content.html, but it can't do.
I created simple example
demo
I try move "<script src="menu.js"></script>" to menu.html
Your code moves away from the whole idea of writing single page app with angular. I have updated it to give you basic idea of how you would do the routes and share templates and use controller.
Check out the plunkr
html
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="menu.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script data-require="ui-router#*" data-semver="0.2.15" src="https://cdn.rawgit.com/angular-ui/ui-router/805e69bae319e922e4d3265b7ef565058aaff850/release/angular-ui-router.js"></script>
<script src="menu.js"></script>
<script src="index.js"></script>
</head>
<body>
<div id="menu" ng-include="'menu.html'"></div>
<div ui-view></div>
</body>
</html>
js
angular.element(document).ready(function() {
angular.bootstrap(document, ["app"]);
});
angular.module('app',['moduleContent', 'moduleMenu', 'ui.router']);
var app = angular.module('app');
app.config(function($stateProvider) {
$stateProvider
.state('index', {
url: "",
templateUrl: "first.html",
controller: 'firstCtrl'
})
.state('second', {
url: "/second",
templateUrl: "second.html"
})
});
app.controller('firstCtrl', ['$scope', function($scope) {
$scope.page = "first";
}]);
//Conttent module
angular.module('moduleContent',[])
.controller('contentCtrl', contentCtrl);
function contentCtrl(shareData)
{
shareData.currentPage = 0;
}

how to make directive in angular of owl carousel?

can you please tell me how to make dirctive in angular js .I need to use owl carousel plugin in js as I did in jqm fiddle http://jsfiddle.net/ezanker/o9foej5L/1/
.I need to make same thing in angular using directive can you please tell me how I will implement this using directive
http://plnkr.co/edit/4ySYwsqrBKUJUj6MwoRY?p=catalogue
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css#3.x" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link data-require="bootstrap-css#3.x" data-semver="3.2.0" rel="stylesheet" href="http://www.owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.css" />
<link data-require="bootstrap-css#3.x" data-semver="3.2.0" rel="stylesheet" href=" http://www.owlgraphic.com/owlcarousel/owl-carousel/owl.theme.css" />
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="ui-bootstrap#0.10.0" data-semver="0.10.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="script.js"></script>
<script src="http://www.owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.js"></script>
</head>
<body>
<div id="owl-demo">
<div class="item"><p>one</p></div>
<div class="item"><p>two</p></div>
<div class="item"><p>three</p></div>
<div class="item"><p>four</p></div>
</div>
</body>
</html>
You can use a directive like this:
app.directive('owlCarousel', function() {
return {
restrict: 'A',
scope: {
owlOptions: '='
},
link: function(scope, element, attrs) {
$(element).owlCarousel(scope.owlOptions);
}
};
});
And on the HTML add it as an attribute:
<div owl-carousel owl-options="owlOptions">
...
</div>
Demo
Here is my general solution. This works with ngrepeat and with refresh data of the scope. The trick is add a directive for the last item, so the init will be fired when the last item is in the dom.
<div owl-slides-count="3" owl-carousel="">
<div ng-repeat="post in posts" owl-carousel-item="">
...
</div>
</div>
... the js
.directive('owlCarousel', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.initCarousel = function () {
// hacky ondomready
$timeout(function hackyDomReady() {
// if is already initialized destroy and re create it
// $(element).data().owlCarousel <- owl 2
if ($(element).data('owlCarousel')) { // <- owl 1
// $(element).trigger('destroy.owl.carousel'); // <- owl 2
$(element).data('owlCarousel').destroy();// <- owl 1
}
$(element).owlCarousel({
autoPlay: 10000,
navigation: true,
items: attrs.owlSlidesCount
});
});
};
}
};
}])
.directive('owlCarouselItem', [function () {
return {
restrict: 'A',
transclude: false,
link: function (scope, element) {
if (scope.$last) {
scope.initCarousel();
}
}
};
}])

Categories