Parameter not passed to next page - AngularJS - javascript

I want to pass a parameter to the next page onclick of a button.
I have tried as below; on the first page I have a textarea and I want to pass that value to the next page on button click using AngularJS, I have tried as below, but it's not working.
index.html
<!doctype html>
<html ng-app="project">
<head>
<title>Angular: Service example</title>
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script src="sample.js"></script>
</head>
<body>
<div ng-controller="FirstCtrl">
<h2>{{name}}</h2>
<input ng-model="thing.x"/>
</div>
<input type="button" value="send" onclick="send()">
<script>
function send(){
window.location ="second.html";
}
</script>
</body>
</html>
sample.js
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : {
x : 100
}
};
});
function FirstCtrl($scope, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
}
function SecondCtrl($scope, theService) {
$scope.someThing = theService.thing;
$scope.name = "Second Controller!";
}
second.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Passed data</title>
<script src="sample.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div ng-controller="SecondCtrl">
<h2>{{name}}</h2>
<input ng-model="someThing.x"/>
</div>
<br>
</body>
</html>
Please can you help me to figure it out?

First read this https://docs.angularjs.org/guide/$location
Remove send() function
function FirstCtrl($scope, $location, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
$scope.send = function(){
$location.path('/second').search({id: 12});
};
}
<input type="button" value="send" ng-click="send()">

To send the parameter to next page you have to use $location service.
$location.path('/second').search({id: 12});
But again this will not work for you as you are not using AngularJS for routing , you are using JS for that. I suggest following this PhoneCatApp to learn Angular basics

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!

AngularJS error loading Controller

I have a really dumb problem but I don't know how to fix it. I have this index.html file with AngularJS loaded. I'm using Plunker to test the code:
<!DOCTYPE html>
<html ng-app="">
<head>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="BodyController">
<h1>{{ message }}</h1>
</body>
</html>
And this script.js file with this information:
var BodyController = function($scope) {
$scope.message = "Hi Angular!"
}
In the inspector it says:
Error: [ng:areq] Argument 'BodyController' is not a function, got undefined
The script is loaded. I have defined the controller in the JS file and attach the ng-controller directive, so I don't know where this can fail.
This is very basic of AngularJS.
You first need to create a module:
var fooApp = angular.module("foo", [])
And then, register your controller there:
var BodyController = function($scope) {
$scope.message = "Hi Angular!"
}
fooApp.controller("BodyController", BodyController);
And, in your HTML tag, change your ng-app like this:
<html ng-app="foo"></html>
You need to add the controller to your Angular module.
angular.module('app', [])
.controller('BodyController', function($scope) {
$scope.message = "Hi Angular!"
})
More info on how to setup a controller
https://docs.angularjs.org/guide/controller
In HTML, add
<html ng-app="myapp">
and the script is
angular.module('myapp', []).controller('BodyController',BodyController)
There were several errors
ng-app was not set
angular module was not defined
the controller was not defined
angular.module('app', [])
.controller('BodyController', function($scope) {
$scope.message = "Hi Angular!"
});
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="BodyController">
<h1>{{ message }}</h1>
</body>
</html>

Beginners help to Angular JS debugging via console errors

AngularJS is new to me (and difficult). So I would like to learn how to debug.
Currently I'm following a course and messed something up. Would like to know how to interpret the console error and solve the bug.
plnkr.co code
index.html
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form action="searchUser" ng-submit="search(username)">
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="submit" value="search">
</form>
<div>
<p>Username found: {{user.name + error}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>
script.js
(function() {
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
};
var onError = function(reason) {
$scope.error = "could not fetch data";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
$scope.username = "angular";
$scope.message = "GitHub Viewer"; };
app.controller("MainController", MainController);
}());
The console only says
searchUser:1 GET http://run.plnkr.co/lZX5It1qGRq2JGHL/searchUser? 404
(Not Found)
Any help would be appreciated.
In your form, action you have written this
<form action="searchUser"
What this does is it will try to submit to a url with currentHostName\searchUser, so in this case your are testing on plunker hence the plunker url.
You can change the url where the form is submitted. Incase you want to search ajax wise then you dont even need to specify the action part. You can let your service/factory make that call for you.
Though not exactly related to debugging this particular error, there is a chrome extension "ng-inspector" which is very useful for angularJS newbies. You can view the value each of your angular variable scopewise and their value. Hope it helps!
Here is the link of the chrome extension: https://chrome.google.com/webstore/detail/ng-inspector-for-angularj/aadgmnobpdmgmigaicncghmmoeflnamj?hl=en
Since you are using ng-submit page is being redirected before the response arrives and you provided any action URL as searchUser which is not a state or any html file so it being used to unknown address, it is async call so it will take some time you can use input types as button instead of submit.
Here is the working plunker.
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form >
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="button" ng-click="search(username)" value="search">
</form>
<div>
<p>Username found: {{user.name + error}} {{user}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>

Error in Angular JS

I included angular js in my asp.net mvc project but when i call object in controller
the angular js expressions do not evaluate
here is the app.js code please suggest
var app = angular.module('app', []);
app.controller('createController', createController);
and here is the createController code
var createController = function ($scope) {
$scope.mydata = 'I work!';
}
here is what i include in html
<html ng-app="app">
<script src="~/Scripts/angular.min.js"></script>
<script src="~/appAjs/app.js"></script>
<script src="~/appAjs/controllers/createController.js"></script>
<div ng-controller="createController">
{{scope.mydata}}
{{6+9}}
from your code, I can only suspect two things
your javascript does not have the proper scope
do not use the word scope in your "scope" code
first part: javascript scope:
Always use an IIFE, in your case your code should look like:
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
second part: don't use the word scope
in your HTML, you should not use the word scope as it's already inherit in your controller as that's the model you are passing to the "view"
hence, your code should look like:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
</body>
</html>
the result is:
I work! 15
live code in JSBIN so you can check it out.
your HTML page, all together should look like this:
if you have only one file
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>My AngularJs App</title>
</head>
<body>
<!-- HTML -->
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
<!-- AngularJS required -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<!-- AngularJS code -->
<script>
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
</script>
</body>
</html>
if you're using 2 files
file index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>My AngularJs App</title>
</head>
<body>
<!-- HTML -->
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
<!-- AngularJS required -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<!-- AngularJS extra files -->
<script src="createController.js"></script>
</body>
</html>
file createController.js (in the same folder as index.html)
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
I think the problem may well be the order in which you are including your scripts:
Try the following:
<script src="~/Scripts/angular.min.js"></script>
<script src="~/appAjs/controllers/createController.js"></script>
<script src="~/appAjs/app.js"></script>
Reasoning is that app.js tries to define a controller using a function that has not been defined when the function is run.
Points that {{scope.data}} should be {{data}} are correct, but do not explain {{6+9}} not working.
You need to create the controller in the context of the app module.
Your app.js should just have
angular.module('app', []);
and your createController code should look similar to this
angular.module('app')
.controller('createController', function ($scope) {
$scope.mydata = 'I work!';
});
You need to change the expression from
{{scope.mydata}}
to
{{mydata}}
Expression have access to scope and no keyword is required to access a scope object.

What's the Angular way to update the scope?

I have a simple two-way binding setup with angular, and I added a plain javascript function that updates the value based off of the "alt" tag of an image a user clicks on. The problem is that when I hit save, the data doesn't update until I click inside the textbox and add a space. What's the best way to get around this?
http://plnkr.co/edit/j6tPYYUqvRyvfs32mcrW?p=preview
angular.module('copyExample', [])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.master = {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master = angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}
]);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
</head>
<body ng-app="copyExample">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name:
<input type="text" ng-model="user.name" id="name" />
<br />
<img src="http://placehold.it/100&text=John" onclick="changeText(alt)" alt="John" />
<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
function changeText(value) {
document.getElementById('name').value = value
}
</script>
</body>
</html>
working fiddle - http://jsfiddle.net/lwalden/b2p7pu7g/
If you are already using Angular then don't write a plain vanilla javascript function for the image click event - use Angular.
Also it's recommended not to use the alt attribute in this way. You could use a data- attribute instead.
Additional attributes within a tag to pass values to a function

Categories