ng-click event not working with ocLazyLoad - javascript

I have a basic Angular.js app which is using ocLazyLoad for loading the application files. I am using the skeleton of the sbAdminApp template.
My problem is that when I use a template with an ng-click event, the click event is not being fired. It is not a scope problem because when I print the function's content to the view it is shown.
Here is some of my code:
For loading the files using ocLazyLoad:
$stateProvider.state('dashboard.importLotteries', {
templateUrl: '/Scripts/app/views/importLotteries.html',
url: '/importLotteries',
controller: 'LotteriesCtrl',
resolve: {
loadMyFiles: function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'sbAdminApp',
files: [
'/Scripts/app/scripts/services/lotteriesService.js',
'/Scripts/app/scripts/controllers/lotteries.js'
]
})
}
}
}
This is the importLotteries.html template file:
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Import Lotteries
</div>
{{importLotteries.toString()}}
<div class="panel-body">
<input type="button" ng-click="importLotteries()" value="Import"/>
<span ng-model="importStatus">
</span>
</div>
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
and this is the controller's code:
'use strict';
angular.module('sbAdminApp')
.controller('LotteriesCtrl', function ($scope, lotteriesService) {
$scope.importLotteries = function () {
alert("importing");
$scope.importStatus = "Loading...";
};
});
The result view looks like this:
So as you can see, the function exists on the scope but the click event is not firing and I don't get any errors.
I tried to search for a solution online for sometime now and couldn't find one, so any help will be greatly appreciated!
After further investigating the issue, I see that the event function (importLotteries) is undefined in the scope, but when I change the value to a string instead of a function the scope value is correct.

Try attaching a ng-href or href to the link and it'll be fired.
<input type="button" ng-click="importLotteries()" ng-href='#' value="Import"/>
Source:
[1] Angular ng-click with call to a controller function not working

Related

Show a div with AngularJS

I am searching how to show a div with AngularJS. I read some topic on StackOverflow but when I try to apply them, it doesn't works for my case...
This is my HTML code :
<div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue" class="ng-cloak">
Blablabla
</div>
<div id="DivWhereIsMyButton" class="clearfix" ng-controller="controllerBubble">
Another div where is my button
<div id="containerButton" ng-controller="controllerDependance">
<button class="btn btn-danger btn-lg pull-right"
ng-click="showAlert()">View dependances
</button>
</div>
</div>
This is the controller :
d3DemoApp.controller('controllerBubble', function () {
});
d3DemoApp.controller('controllerDependance', function ($scope) {
$scope.myvalue = false;
$scope.showAlert = function(){
$scope.myvalue = true;
};
});
I initially thought, it is controllerOther take the hand and cancel the controllerDiv but even if I separate the both, it doesn't works. The problem is I am obligated to put the both in two differents controllers.
I have two controllers, controllerDependance and controllerBubble. My div to show is in the controllerDependance. My button is in a div controllerBubble and I can't move it. So I would like to wrap it in a div controllerDependance.
I make a Plunker to show you the problem : https://plnkr.co/edit/z1ORNRzHbr7EVQfqHn6z?p=preview
Any idea ?
Thanks.
Put the div you want to show and hide inside the controller. It needs to be within the scope of the controller, otherwise your controller function cant see it. Also, consider what you are trying to accomplish with the nested controllers, I often find them unnecessary.
<div id="divButton" class="clearfix" ng-controller="controllerOther">
<div id="buttonToShowDiv" ng-controller="controllerDiv">
<button class="btn btn-danger btn-lg pull-right" ng-click="showAlert()">Show my div</button>
<div id="myDiv"ng-show="myvalue" class="ng-cloak">
Blablabla
</div>
</div>
</div>
I notice in your original example you are declaring ng-controller="controllerDependance" twice in the DOM. I have never tried this before, but I can imagine this will cause problems. From the angular documentation on controllers
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope
I imagine that this is what is causing you problems. You have to have the div you want to show/hide within the scope of your controller.
I got your plunkr working, you can see my version here: https://plnkr.co/edit/NXbsVFMNHR8twtL8hoE2?p=preview
The problem was stemming from you declaring the same controller twice, and more importantly, the div to show/hide was using ng-show with a value from your mainController. But your div was outside that controller. So ng-show cant see the value. The div has to be withing the scope of the controller
You are using two different controllers which have different $scopes therefore their values are not connected! To show or hide a div is really simple in angular:
<div id="divButton" class="clearfix" ng-controller="myController">
<div id="buttonToShowDiv">
<button class="btn btn-danger btn-lg pull-right" ng-click="showAlert()">Show my div</button>
</div>
<div id="myDiv" ng-show="myvalue" class="ng-cloak">
Blablabla
</div>
</div>
And the script side just almost the same:
d3DemoApp.controller('myController', function AppCtrl ($scope) {
$scope.myvalue = false;
$scope.showAlert = function(){
$scope.myvalue = true;
};
});
Since you question was how to show elements using angular, I took the liberty of using just one controller.
Create a factory that will return an object and let your controllers work with a reference to the same object:
var d3DemoApp = angular.module('app', [])
d3DemoApp.factory('MyValue', function () {
return { value: false };
});
d3DemoApp.controller('controllerBubble', function ($scope, MyValue) {
$scope.myvalue = MyValue;
});
d3DemoApp.controller('controllerDependance', function ($scope, MyValue) {
$scope.myvalue = MyValue;
$scope.showAlert = function(){
$scope.myvalue.value = true;
};
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-app="app">
<div ng-controller="controllerBubble" class="clearfix">
<div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue.value" class="ng-cloak">
Blablabla
</div>
</div>
<div id="DivWhereIsMyButton" class="clearfix" ng-controller="controllerBubble">
Another div where is my button
<div id="containerButton" ng-controller="controllerDependance">
<button class="btn btn-danger btn-lg pull-right" ng-click="showAlert()">View dependances</button>
</div>
</div>
</div>
</body>
</html>

ng-change and ng-click not triggering events in controller

I'm trying to create a radio type button selection in AngularJS. Here is my code.
HTML code:
<!-- Page Content -->
<div id="page-wrapper">
<div class="container-fluid">
<h3 class="page-header">Create Products</h3>
<div class="media-list" data-toggle="buttons">
<label class="btn btn-default col-md-2 custom-thumbnail">
<input type="radio" ng-model="platformSel" ng-change="tileSelect(value)" value="win" name="platform-selection" id="win-tile" >
<i class="center-block fa fa-windows fa-5x"></i>
<span class="text-center">Windows</span>
</label>
<label class="btn btn-default col-md-offset-custom col-md-2 custom-thumbnail">
<input type="radio" ng-model="platformSel" ng-change="tileSelect(value)" value="mac" name="platform-selection" id="mac-tile">
<i class="center-block fa fa-apple fa-5x"></i>
<span class="text-center">MAC</span>
</label>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
Controller code:
(function() {
'use strict';
function config($routeProvider) {
$routeProvider
.when('/createProduct', {
templateUrl: 'app/components/createProduct/createProductView.html',
controller: 'createProductCtrlr'
});
}
function createProductCtrlr($scope, $rootScope, $location) {
$scope.platformSel = '';
$scope.tileSelect = function(target) {
console.log(target + " selected");
};
}
angular
.module('pacman')
.controller('createProductCtrlr', ['$scope', '$rootScope', '$location', createProductCtrlr])
.config(['$routeProvider', config]);
})();
I don't see any call happening in 'tileSelect' function. I have no clue why.
Any help is appreciated. I'm new to Angular JS.
Is there any error in JavaScript console? As mentioned before you are missing ng-app and ng-controller directives.
<div id="page-wrapper" ng-app="pacman" ng-controller="createProductCtrlr">
The rest of the code almost correct but since you bind the radio to a model variable there is no need for passing argument in ng-change function.
$scope.tileSelect = function() {
console.log($scope.platformSel + " selected");
};
Check this fiddle
Debugging and fixing stuff is real hard. Not as simple as writing code from scratch.
The reason being is, 'data-toggle=buttons' just toggles the bootstrap UI and doesnt make any function calls. Remove the line from html line where class="media-list" and it works.
Answer:
data-toggle="buttons" just toggles the twin button group. Doesnt allow to make function calls.

View Source functionality using AngularJS

The feature I'm trying to implement is a toggle view source button so the user can view the source of a given element then copy the text.
Using the ngRoute module, my views are coming through ng-view:
<div id="code" ng-view=""></div>
I would like the HTML to be output to:
<div id="html-text-output"></div>
I've tried using the $sanitize function but I'm not sure it is appropriate for my solution. Below is the code currently in my controller:
angular.module('App')
.controller('outputHtmlCtrl', function ($scope, $element, $sanitize) {
$scope.isOutputToggled = true;
var sanatizedHtml = $sanitize($('#email-frame-code').html());
$scope.toggleHtmlOutput = function() {
$scope.isOutputToggled = $scope.isOutputToggled === false ? true: false;
$('#html-text-output').append("<div>"+"'"+sanatizedHtml+"'"+"</div>");
}
});
My markup is below:
<div id="email-frame-code__container" ng-controller="outputHtmlCtrl">
<div class="browser-header">
<span class="browser-header__icon" ng-click="toggleHtmlOutput()"></span>
</div>
<div id="email-frame-code" ng-class="{closed: isOutputToggled}">
<div id="html-text-output"></div>
<div id="code" ng-view=""></div>
</div>
</div>
My end goal for this is like the 'Fancy Version' here: https://css-tricks.com/examples/ViewSourceButton/
But on a target element, not the whole page.

Angular JS :Hide/Close a Modal

I am facing issues while closing the Modal in Angular JS
HTML
<div class="container">
<div class="col-md-12" id="gridSet">
<div class="gridStyle adjustViewPort" ng-grid="gridOptions"></div>
// Here is the HTML template for MODAL.
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-body">
<p>No Events Found</p>
<p><button class="btn btn-primary" ng-click="myClickEvent()">OK</button></p>
</div>
</script>
</div>
</div>
And in controller.js looks like
$scope.modalInstance=$modal.open({templateUrl: 'myModalContent.html'});
//This should run. But, every time only Cancelled is logged.
$scope.modalInstance.result.then(function() {
console.log('Success'); // This is never executed.
}, function() {
console.log('Cancelled');
})['finally'](function(){
$scope.modalInstance = undefined
});
I have tried to hide the modal by this.$hide(); in myClickEvent But, the function is not called at all.
Code from Plunker from which I have copied the code.
Looking for 1) Hide the modal after few seconds using $timeout
2) Close the modal when user selects OK.
UPDATE
Issue is the Code in Plunker Shows $modalInstance as dependency which I am not able to inject.
Function 'ng-click="myClickEvent()"' calls a function in controller which is as below.
$scope.myClickEvent=function(){
alert('the function is called.');
}
But, the there is no alert.
Thanks for help in advance.
Use close() method:
$scope.close = function () {
$modalInstance.close();
};
<button class="btn btn-warning" ng-click="close()">Close</button>

Angular data - having trouble binding updated values to scope (using slider)

I'm trying to use Angular to create a tool that accepts user input from a slider tool, and automatically updates an "estimate" field whenever the values are changed. However, the data only seems to be binding on the way to the view; the user input is displayed, but doesn't seem to register in the scope.
Here's the HTML:
<h3 ng-controller="calcController" ng-model="estimate" class="floating-menu">${{estimate}}</h3>
<form ng-controller="calcController" method="post" action="/estimate">
<div class="container">
<div class="vals">${{values.insurance}}</div>
<div id="insurance-slider">
<slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.insurance" ng-change="changeVal()" translate="currencyFormatting"></slider>
</div>
<div class="container">
<div class="vals">${{values.lease}}</div>
<div id="lease-slider">
<slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.lease" translate="currencyFormatting"></slider>
</div>
</div>
</form>
Here's the Angular:
//create the module
angular.module('Breeze', ['ngRoute', 'ngResource', 'ui.slider'])
.config(function($routeProvider) {
$routeProvider
// route for the calculator page
.when('/', {
templateUrl: 'partials/calculator.html',
controller: 'calcController'
});
})
// create the controller and inject Angular's $scope
.controller('calcController', function($scope, $http) {
$scope.values = {
// Default values
insurance: 125,
lease: 125,
};
$scope.estimate = $scope.values.insurance + $scope.values.lease
}
// Formatting for scale bar
$scope.currencyFormatting = function(value) {
return value.toString() + " $";
}
})
I've tried adding a $watch and a $broadcast function but can't seem to get them working.
This is what it looked like in Angular:
$scope.$watch("values", function(newVal, oldVal, scope) {
scope.estimate = addVals();
})
$scope.changeVal = function() {
$scope.estimate = addVals();
console.log('hi')
$scope.estimate = $scope.values.insurance + $scope.values.lease
}
Ideas?
You are using two nested ng-controller="calcController"in your HTML. Hence two instanciations of the controller (two $scope) which will have their own estimate value, so when you update the inner estimate, the upper one is not aware of that.
You should remove the second ng-controller in your <form> (if the controller were different, then you would put the estimate variable in an object such as $scope.model.estimate so properties inheritance between the two controllers actually work. But in your case there is no reason to have two controllers).
Also, you should remove that ng-model="estimate" in your <h3> tag, which has no effect.
Just setting them equal in the beginning wont work. In your view, instead of having an estimate field just use this
<div ng-controller="calcController" ng-app="Breeze">
<h3 ng-model="estimate" class="floating-menu">${{values.insurance + values.lease }}</h3>
<form method="post" action="/estimate">
<div class="container">
<div class="vals">${{values.insurance}}</div>
<div id="insurance-slider">
<slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.insurance" ng-change="changeVal()" translate="currencyFormatting"></slider>
</div>
<div class="container">
<div class="vals">${{values.lease}}</div>
<div id="lease-slider">
<slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.lease" translate="currencyFormatting"></slider>
</div>
</div>
</div>
</form>
</div>
This will keep them adding as the values change.
Another thing that would be breaking is that you have two controller calls to the same controller and no app. Need to change it as below with the new div and remove the rest of the ng-controllers.
Also, make sure that you have the ui slide javascript file included on your page.
Did you try to bind to object instead of primitive type?
$scope.values.estimate = $scope.values.insurance + $scope.values.lease
see similar question here:
Angularjs: 2 way binding not working in included template
Here is a fiddle http://jsfiddle.net/U3pVM/9330/

Categories

Resources