using jQuery function in AngularJS - javascript

codepen this is the working code
I have a working code for changing the status of the network.
But I used jQuery to achieve it and now I am using angular app for the same thing.
Could you please help me.
Below is the Angular Code I have tried from already existing plunker:
Plunker
HTML:
<!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="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
Hello {{name}}! {{online}}
</body>
</html>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
app.run(function($window, $rootScope) {
$rootScope.online = navigator.onLine;
$window.addEventListener("offline", function () {
$rootScope.$apply(function() {
$rootScope.online = false;
});
}, false);
$window.addEventListener("online", function () {
$rootScope.$apply(function() {
$rootScope.online = true;
});
}, false);
});

Use ng-class like this:
<div id="connection" ng-class="{'connected': online == true}">Online<div></div></div>
Here is your corrected Plunker
Hope this is what you wanted.

http://plnkr.co/edit/C2oJAYtEbb2lMixY2rVa?p=preview
<div id="connection" ng-class="{'connected': online, 'disconnected': !online}">
<span ng-if="$root.online">Online<div></div></span>
<span ng-if="!$root.online">Offline<div></div></span>
</div>
Note that with this approach, the initial state of 'connecting...' is not handled.

Related

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 use custom directive on Input fields in Angular 1.x?

I'm trying to modify the input element using a custom AngularJS directive. Basically I want to replace any <input type="country"> fields with a country drop-down.
But the directive doesn't seem to work with input fields. If I change it to any other tag, it works?
Here is the code:
angular.module('plunker', [])
.controller('MainCtrl', function ($scope) {
$scope.name = 'World';
});
angular.module('plunker')
.directive('input', function() {
return {
restrict: 'E',
scope: {ngModel: '=?'},
link: function(scope, elem, attr) {
if(attr.type === 'country') {
elem.html('html code for select');
alert(elem);
}
}
};
});
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
Name: <input type="country" ng-model="name"/> <br/>
</body>
</html>
Can someone please explain and suggest a workaround?
P.S. I've also tried doing this in the directive, but it doesn't work either!
replace: true,
template:'<div>hello</div>'
P.S. I know I can use a ng-country or some other custom tag but I want to change input tag only because I want learn why this is happening or possibly find out what I'm doing wrong?
Latest Update:
Your code is just setting the html on the element, instead of replacing it. You would want to use replaceWith instead like this:
var app = angular.module("TestApp",[]);
app.controller("TestController", function($scope){
$scope.message = "Input Directive Test"
});
app.directive("input", function() {
return {
restrict: "E",
link: function(scope, elem, attr) {
if(attr.type === "country") {
var select = angular.element("<select><option>USA</option></select>");
elem.replaceWith(select);
}
}
}
});
And here's the JSBin: https://jsbin.com/juxici/4/edit?html,js,output
Initial Version of my answer:
Here's an example that works without any issues when 'replace' and 'template' are used. I'm not checking for type and such, but you could do that in the linker code.
JSBin: https://jsbin.com/juxici/2/edit?html,js,output
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</head>
<body ng-app="TestApp">
<div ng-controller="TestController">
<h2>{{message}}</h2>
<input type="country" ng-model="name"/>
</div>
</body>
</html>
Javascript:
var app = angular.module("TestApp",[]);
app.controller("TestController", function($scope){
$scope.message = "Input Directive Test"
});
app.directive("input", function() {
return {
restrict: "E",
replace: true,
template:"<select><option>USA</option></select>"
}
});

AngularJS replace using regex on template

I have the following markup that shows a value from ng-model.
<a ng-click="downloadDocument()">{{document.content.replace(/\d+\_/,"")}}</a>
Before each document.content I add a number and an underscore, smth like "12122141_document.txt". I want to replace this part by using this regex /\d+_/
This throws an error on angularJS, although {{ document.replace(" ","") }} works.
Is the only way to solve this a directive or am I doing something wrong?
Plunker: http://embed.plnkr.co/sh54XZwSIlYnmvY0eTIt/preview
Cheers,
Alex
I modified your Plunker-Demo and it works pretty fine.
Hint: Don't use $scope namespaces like "document". Its reserved/used by the client.
var app = angular.module('plunker', []);
Controller
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.fileName = {
content : function(){
return '1233_test.txt'.replace(/\d+\_/,"");
}
}
$scope.mpla = function () {
console.log('clicked');
}
});
View
<!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.14/angular.js" data-semver="1.3.14"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<a ng-click="mpla()" ng-bind="fileName.content()"></a>
</body>
</html>

Why isn't my Angular.js GET request working?

My goal is to spin a servo for a certain amount of seconds on a HTML button click. I am using an Arduino Yun as my microcontroller.
When I type in the URL directly the servo spins as it should. When I click on these buttons using the Angular.js GET request nothing happens. Even a regular form submit button works.
Is there something missing from my code?
Is there an easier way to accomplish this?
Here is my front-end code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
<title>winner's cat Feeder</title>
</head>
<body>
<div ng-controller="ArduinoCtrl" class="container">
<button ng-click="setServo(1)" class="btn">3 Seconds(Food)</button>
<button ng-click="setServo(2)" class="btn">9 Seconds(Food)</button>
</div>
</body>
</html>
<script type="text/javascript">
function ArduinoCtrl($scope, $http)
{
$scope.setServo = function (setting)
{
var url = "http://192.168.1.79/arduino/" + setting
$http.get(url);
}
}
</script>
If I just type in the URL in my browser with the setting value of 1 or 2 the servo works fine.
Please see working demo
var app = angular.module('app', []);
app.controller('ArduinoCtrl', function($scope, $http) {
$scope.response = {};
$scope.progress = false;
$scope.setServo = function(setting) {
$scope.progress = true;
var url = "http://192.168.1.79/arduino/" + setting
$http.get(url).then(sucess, error).then(function() {
$scope.progress = false;
});
function sucess(response) {
angular.copy(response, $scope.response)
}
function error(response) {
angular.copy(response, $scope.response)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div ng-app="app">
<div ng-controller="ArduinoCtrl" class="container">
<button ng-click="setServo(1)" class="btn">3 Seconds(Food)</button>
<button ng-click="setServo(2)" class="btn">9 Seconds(Food)</button>
<p ng-show="progress">Please wait</p>
<div ng-hide="progress">
<hr/>
<p>Response</p>
<pre>{{response | json}}</pre>
</div>
</div>
</div>
You need to add the ng-app directive and add your controller to a module:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
<title>winner's cat Feeder</title>
</head>
<body ng-app="myApp">
<div ng-controller="ArduinoCtrl" class="container">
<button ng-click="setServo(1)" class="btn">3 Seconds(Food)</button>
<button ng-click="setServo(2)" class="btn">9 Seconds(Food)</button>
</div>
</body>
</html>
<script type="text/javascript">
function ArduinoCtrl($scope, $http)
{
$scope.setServo = function (setting)
{
var url = "http://192.168.1.79/arduino/" + setting
$http.get(url);
}
}
angular.module("myApp", []).controller("ArduinoCtrl", ArduinoCtrl);
</script>

How to inherit from base controller using "controller as" syntax?

Here is a snippet demonstrating how to inherit from a base controller using $controller and $scope:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $controller) {
$controller('BaseCtrl', {
$scope: $scope
})
});
app.controller('BaseCtrl', function($scope) {
$scope.name = 'World';
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>
How can I do the same using "controller as" syntax? This snippet demonstrates what I am after, but it doesn't work:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $controller) {
$controller('BaseCtrl', {
$scope: $scope
})
});
app.controller('BaseCtrl', function() {
this.name = 'World';
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as main">
<p>Hello {{main.name}}!</p>
</body>
</html>
You could use controller as syntax (or just use the ctrl instance returned by $controller provider) and use angular.extend. But i don't think there is another way implicitly angular would do this, since "controller as" syntax ultimately places the controller instance on the respective scope as a property name specified as alias. But this really isn't inheritance, but utilizing object extension.
var ctrl = $controller('BaseCtrl as base', { //You don't really need to use as syntax here though
$scope: $scope
});
angular.extend(this, ctrl);
//or
$controller('BaseCtrl as base', { //You don't really need to use as syntax here though
$scope: $scope
});
angular.extend(this, $scope.base); //With as syntax
Or you could use prototypical inheritance at the implementation level of the controller constructors itself. There are lots of syntactic sugars available, typescript's extends there is another nice and simple example here as well.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $controller) {
var ctrl = $controller('BaseCtrl as base', {
$scope: $scope
});
angular.extend(this, ctrl);
});
app.controller('BaseCtrl', function() {
this.name = 'World';
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as main">
<p>Hello {{main.name}}!</p>
</body>
</html>

Categories