Angular JS ngShow and ngHide - javascript

I can't figure out why the ngShow and ngHide directives aren't working. Here is a simplified version of the problem.
<div id="callFunction" ng-click="myFunction()">content here</div>
<div id="contactInfo" ng-show="showContent">content here</div>
In controller
$scope.showContent = false;
$scope.myFunction = function() {
$scope.showContent = true;
}
The "contactInfo" div never shows when I click the "callFunction" div.

Your problem is known in the javascript world as "the dot." The idea is that in javascript, native values are passed by value whereas object values are passed by reference. Try changing your view to this:
<div id="callFunction" ng-click="myFunction()">...</div>
<div id="contactInfo" ng-show="content.Show">...</div>
and change your controller to:
$scope.content.Show = false;
$scope.myFunction = function() {
$scope.content.Show = true;
}
The reason this would work is because you're now passing an object around and manipulating an object instead of just manipulating a value. Essentially, think of it as a "sub-scope" problem, where your "div" is spawning its own scope under the view so that variable you're referencing is a native type, it passes by value. Therefore the function updates the parent value but not the child value.
For more information: http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html

http://jsfiddle.net/aesmzz6q
HTML:
<div ng-controller="theCtrl">
<div id="callFunction" ng-click="myFunction()">content here</div>
<div id="contactInfo" ng-show="showContent">content here</div>
</div>
JavaScript:
angular.module('appName', [])
.controller('theCtrl', ['$scope', function ($scope) {
$scope.showContent = false;
$scope.myFunction = function() {
$scope.showContent = !$scope.showContent;
}
}]);
angular.element(document).ready(function() {
angular.bootstrap(document, ['appName']);
});
There doesn't seem to be anything wrong with what you have. Here's a link to a working example.aesmzz6q

This works for me. I think your problem might be elsewhere.
HTML:
<div ng-controller="MyCtrl">
<div id="callFunction" ng-click="myFunction()">content here</div>
<div id="contactInfo" ng-show="showContent">content here</div>
</div>
JavaScript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.showContent = false;
$scope.myFunction = function() {
$scope.showContent = true;
}
}
I have to include code to allow the JSFiddle link.

This works fine:
<!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 data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.11/angular.js" data-semver="1.3.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div id="callFunction" ng-click="myFunction()">content here</div>
<div id="contactInfo" ng-show="showContent">content here</div>
</body>
</html>
I've added a fiddle: http://plnkr.co/edit/S06ufeHI2j5lKs5LxbRT?p=preview
I have also fixed your fiddle there were a number of things wrong http://jsfiddle.net/97nkv1v1/4/

Related

How to toggle between elements in angularJS

I have two elements, only one of them is supposed to show up at a time while the other element stays hidden until the visible element is made to disappear (button click), here an example of the last logic I have tried to use.
.......
<div ng-show='show'>
Visible element
<button ng-click='toggle()'> Toggle </button>
</div>
<div ng-hide='show'>
Hidden Element
</div>
.......
And I have something like this in my controller
........
$scope.show = true;
$scope.toggle = function(){
$scope.show =!$scope.show;
}
.........
Now, anytime I click the button, the first element will disappear but the second element will not show. Please I really need help.
You have to put your button out of the ng-show div like this
<div ng-show='show'>
<div>Visible element</div>
</div>
<div ng-hide='show'>
<div>Hidden Element</div>
</div>
<button ng-click='toggle()'> Toggle </button>
then its work fine. Hope this help...
Here is the solution
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.show = true;
$scope.toggle = function(){
$scope.show =!$scope.show;
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-show='show'>
Visible element
</div>
<div ng-hide='show'>
Hidden Element
</div>
<button ng-click='toggle()'> Toggle </button>
</body>
</html>

How can I use javascript code inside angularjs?

I need to run this code in angularjs.
When I try to execute this model function it is not running.
It is not even showing alert or console.
So what is the way to use this script files in angularjs
Here is my code in example.html:
<div>
{{sample}}
</div>
<div><button ng-click="name()"></div>
<script>
function name(){
alert("text");
}
</script>
If i understand your requirement correctly,
You need to execute a separate java-script function.
For an angular application it is not a proper way to run javascript out of scope of angular.
any if it is absolutely requried you can try replacing ng-click="name()" with onclick="name()"
var app = angular.module("app", []);
app.controller('exampleController', [function() {
this.myFunction = function() {
alert("Iam from angular controller");
}
}]);
function myFunction() {
alert("Iam from javascript");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.myFunction()">click me</button>
<button onclick="myFunction()">click me</button>
</div>
#Update
If you want to use a java script library or function or constants in angularjs the my suggested way is to add a factory or service that ensure the library or function or constants but it is not simple as above solution.Here iam adding a snippet based on above solution
There are some advantages of using following approch :-
It will add dependency injection proprely which is a basic concept behind angularjs
It will ensure that the external function exist before starting app.
It will add more flexibility and control over the java script function in angular.
The below snippet will remove the external access of function and secure your application
This is the best way in which you can add external libraries like jquery loadash or any js libraries to your code
(function() {
function exampleController(myFunction) {
this.myFunction = function() {
alert("Iam from angular controller");
}
this.externalJSFunction = myFunction
};
exampleController.$inject = ['myFunction'];
function myFunctionFactory($window) {
if (!$window.myFunction) {
throw new Error("myFunction is not defined");
}
this.myFunction = $window.myFunction;
/* You can add
$window.myFunction = undefined;
if the function ($window.myFunction) is not required by
some other library or function in window scope
in such cases it gives added security by
restricting access of this from window scope and dis allows modification
*/
return this.myFunction;
}
myFunctionFactory.$inject = ['$window'];
var app = angular.module("app", []);
app.controller('exampleController', exampleController);
app.factory('myFunction', myFunctionFactory);
})();
function myFunction() {
alert("Iam from javascript");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.myFunction()">click me For angular Function</button>
<br/>
<button ng-click="ctrl.externalJSFunction()">click me For external JS Function </button>
<br/>
<button onclick="myFunction()">click me for checking exteranl acess </button>
</div>
your code should be like this....
<!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 data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script >
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name=function(){
alert("text");
}
});
</script>
</head>
<body ng-controller="MainCtrl">
<div>
{{sample}}
</div>
<div><button ng-click="name()">click me</div>
</body>
</html>
You need to give angular js cdn first and then a create a module and controller like above
Here is a sample controller.
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<button ng-click="name()">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = name;
function name(){
alert("text");
}
});
</script>
</body>
You could use a directive, here is an example:
// in your JS source
angular.directive('something', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
alert('yup');
});
}
};
}]);
// in your HTML file
<button type="button" something>Click Me!</button>
This allows you to reuse your various code chunks / functions across your entire project pretty easily.
Another Solution
<!DOCTYPE html>
<html>
<head>
<title>example</title>
<script data-require="jquery#*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.name()">click me to angular</button>
<button ng-click="name()" class="btn">click me to javascript</button>
<script>
var app = angular.module("app", []);
app.controller('exampleController', [function() {
this.name = function() {
alert("angular text");
}
}]);
//JQuery Lib must be included your project
$(document).on('click', '.btn', function() {
eval($(this).attr('ng-click'));
});
function name() {
alert("javascript text");
}
</script>
</body>
</html>
You should be able to run any javascript inside of an angular controller inside of a script tag in an html file.
Your html file should look something more like this:
<!DOCTYPE html>
<html>
<head>
<title>example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.name()">click me</button>
</body>
</html>
<script>
var app = angular.module("app", []);
app.controller('exampleController', [function() {
this.name = function(){
alert("text");
}
}]);
</script>
Create a service layer and glue it inside the controller. Now, you can reuse the created function in multiple controllers.
For implementation,
How can I call javascript function in AngularJS controller?
I hope this helps!

How to call a function inside an Angular component triggered by jQuery events?

I have a third-party component that using jQuery (FineUploader). When a document gets uploaded, it fires an event in javascript/jquery and I need to, at that point, call a function that is inside my Angular component from the jquery code that is outside my Angular component.
The angular button works as expected but I can't get the jQuery button to call the function successfully.
Here's my plunker example code
HTML Page
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script data-require="jquery#1.11.3" data-semver="1.11.3" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script>
function widgetController() {
var model = this;
model.addWidget = function(text) {
alert(text);
}
}
var app = angular.module("app", []);
app.component("widget", {
templateUrl: "template.html",
controllerAs: "model",
controller: [widgetController]
});
</script>
</head>
<body>
<div ng-app="app">
<widget></widget>
</div>
</body>
</html>
Template Page
<center>
<p>The jQuery button below is a representing a third-party component that can't be altered and uses jquery events.</p>
<button id="addAngular" ng-click='model.addWidget("ANGULAR WORKED!!")'>Add widget using Angular</button>
<button id="addJquery">Add widget using jQuery</button>
</center>
<script>
$(function() {
//This is mocking up an event from the third-party component.
$("#addJquery").on("click", function(){
model.addWidget("JQUERY WORKED!!"); //I need to be able to call the Angular function from jQuery
});
});
</script>
I think this may have done the trick but I'm not sure if there is a better answer. Please post an alternate solution if there is a better one.
Here's the working Plunker
HTML Page
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script data-require="jquery#1.11.3" data-semver="1.11.3" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script>
var externalWidget;
function widgetController($scope, WidgetFactory) {
var model = this;
model.factory = WidgetFactory;
model.addWidget = function(text, isUpdatedExternally) {
model.isUpdated = text;
var newWidget = text;
model.factory.widgets.push(newWidget);
if(isUpdatedExternally)
{
$scope.$apply();
}
console.log("updated!");
}
model.checkWidget = function() {
console.log(model.isUpdated);
}
model.isUpdated = "NOT UPDATED";
model.addWidget("Controller initialized Widget");
externalWidget = model;
console.log(externalWidget);
}
var app = angular.module("app", []);
app.factory('WidgetFactory', function () {
var widgetList = [];
var initialWidget = "Factory Initialized Widget";
widgetList.push(initialWidget);
return {
widgets: widgetList
};
});
app.component("widget", {
templateUrl: "template.html",
controllerAs: "model",
controller: ["$scope", "WidgetFactory", widgetController]
});
</script>
</head>
<body>
<div ng-app="app" id="ngApp">
<widget></widget>
<br />
<center><button id="addJquery">Add widget using jQuery</button></center>
</div>
<script>
$(function() {
//This is mocking up an event from the third-party component.
$("#addJquery").on("click", function(){
externalWidget.addWidget("JQUERY WORKED!!!", true);
});
});
</script>
</body>
</html>
Template Page
<center>
<p>The jQuery button below is a representing a third-party component that can't be altered and uses jquery events.</p>
<button id="addAngular" ng-click='model.addWidget("ANGULAR WORKED!!")'>Add widget using Angular</button>
<button id="checkAngular" ng-click='model.checkWidget()'>Check widget using Angular</button>
</center>
<ul>
<li ng-repeat="w in model.factory.widgets">
{{w}}
</li>
</ul>

Calling an AngularJS controller function from outside of it

I have the following code:
app.controller('MatrixExpertCtrl', function($scope,$http){
$scope.PassedMatrix=[];
$scope.GetMatrixFromServer=function(){
$http.get("http://localhost:3000/getmatrixfromdb").success(function(resp){
alert("The matrix grabbed from the server is: " + resp[0].ans);
$scope.PassedMatrix.push(resp[0].ans);
});
};
$scope.DispSize=function(){
alert("testing");
alert("The size is "+$scope.PassedMatrix[0].size) ;
};
//$scope.GetMatrixFromServer();
});
Now, suppose, in HTML, I have something like this:
<div class="col-sm-3 col-md-3 col-lg-3">
<div class="text-center">
<h3>Example Survey</h3>
<p>example paragrah</p>
<p>More random text</p>
<p>ending the paragraphs</p>
<button id="updmat" ng-click="DispSize();" type="button" class="btn btn-default">Updates</button>
</div>
//Much more code
<div id="body2">
<div class="col-sm-6 col-md-6 col-lg-6" style="background-color:#ecf0f1;">
<div ng-controller="MatrixExpertCtrl" ng-app="app" data-ng-init="GetMatrixFromServer()">
<div class="text-center">
Meaning with this:
Is it possible to call a function that is defined inside a controller, from outside of the scope of that same controller?
I need this because the function is manipulating a shared object, owned by the controller in a very very simple fashion (for example, clicking on the button changes the color of a given element).
I am having trouble to make this work, any help will be appreciated.
I think that declaring some data structures as global would help me solving this problem, but, I would like to avoid doing that because, besides it being bad practice, it might bring me more problems in the future.
If i understand your problem correctly than what you basically do have is one utility function which will work on your shared object and do your useful things (i.e. clicking on the button changes the color of a given element) and now you do require the same behaviour in another controller outside of it's scope. You can achieve the same thing in 2 different ways :
1).Create a service and make it available in your controllers like this :
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
changeColour: function() {
alert("Changing the colour to green!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope,
myService) {
$scope.callChangeColour = function() {
myService.changeColour();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callChangeColour()">Call ChangeColour</button>
</body>
</html>
Pros&Cons: More angularistic way, but overhead to add dependency in every different controllers and adding methods accordingly.
2).Access it via rootscope
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalChangeColour = function() {
alert("Changing the colour to green!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalChangeColour()">Call global changing colour</button>
</body>
</html>
Pros&Cons: In this way, all of your templates can call your method without having to pass it to the template from the controller. polluting Root scope if there are lots of such methods.
try removing semicolon
ng-click="DispSize()"
because it binds ng-click directive to the function.

angularjs: simple example - ng-class or ng-controller does not work

pls, help me with next question
I try to implement conditional classes on div blocks using ng-class but have encountered next problem - "it is not working". Example seems to be very simple, I even do not know how else it can be described.
But one more idea - controller does not working instead of ng-class.....i do not know.
Here you can see my code pls, probably you will find smth wrong or give me an advice.
http://plnkr.co/edit/Zm0g4QfkqzTD3h4FWfcp?p=preview
demoApp = angular.module('demoApp',[]);
var controllers = {};
controllers.testCntr = function ($scope)
{
$scope.setClass = function()
{
alert('works');
return True;
}
};
HTML
<!doctype html>
<html ng-app="demoApp">
<head>
<title></title>
<style>
.red
{
color:red;
}
</style>
<script src="angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
</head>
<body>
<div ng-controller="testCntr">
<span ng-class="{red: $scope.setClass()}">Test color</span>
<div>{{$scope.setClass()}}</div>
</div>
</body>
</html>
Thanks for your amendments.
Several problems here.
You can only add one controller at a time with .controller()
In your template, $scope is already the context, so don't include it in the HTML
True should be true
You are missing an ng-app directive
angular.js is not included properly
Your scripts.js is not included
Here's a working version of your Plunkr with the changes above: http://plnkr.co/edit/ybDScjDrrIkH8tBNfIg1?p=preview
When you call a function which is in the scope from the view, just call it like that :
<body ng-app="app">
<div ng-controller="Ctrl">
<span ng-class="{'red': setClass()}">Test color</span>
<div>{{setClass()}}</div>
</div>
</body>
Here the Working Plunkr
You should create an app.js services.js and controllers.js
Your controller should be moved to the controllers.js and look a little something like this.
demoApp.controller('testCntr',function ($scope){
$scope.setClass = (function(){
alert('works');
return True;
})
});
To add the controller to your app you should do this
demoApp.controller('testCntr', function ($scope) {
$scope.setClass = function() {
alert('works');
return True;
}
})
Working Plunkr: http://plnkr.co/edit/LPY94jPJdIJX4pr9K5FY?p=preview
Working Demo:
demoApp = angular.module('demoApp',[]);
demoApp.controller('testCntr', function ($scope) {
$scope.setClass = function() {
alert('works');
return 33;
return True;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" <div="" ng-controller="testCntr">
<span ng-class="{red: $scope.setClass()}">Test color</span>
<div>{{setClass()}}</div>
</div>
your script.js file should be
var app = angular.module('demoApp',[]);
app.controller('testCntr', ['$scope', function($scope) {
$scope.setClass = function() {
return true;
};
}
]);
and html:
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>
<style>
.red {
color:red;
}
</style>
</head>
<body ng-controller="testCntr">
<span ng-class="{red: setClass()}">Test color</span>
</body>
</html>
It may solve your problem
Plunker link: http://plnkr.co/edit/Ftx3M0aG9G8cJtyrn5wj?p=preview

Categories