Change AngularJS urls with ng-model - angularjs

Is there any way to change AngularJS urls with ng-model?
var scotchApp = angular.module('scotchApp', ['ngRoute']);
scotchApp.controller('mainController', function($scope) {
$scope.gettext = function (){
};
});
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="scotchApp">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="eventChange.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="row">
<div class="col-sm-1">Search</div>
<div class="col-sm-3"><input type="text" class="form-control" ng-model="search" ng-change="gettext()"></div>
</div>
</div>
</body>
</html>
I need to change the URL into something like this http://localhost/angulRoute/search=myVal when user type 'myVal' in the search box (actually inside gettext() function with search value)

You can do something like this in your controller:
$scope.query = $location.search().q;
$scope.$watch('query', function(newValue) {
$location.search('q', newValue);
});
You'd need to inject $location into your controller, and make sure in your route config includes:
reloadOnSearch: true
That would result in a URL like http://localhost/myRoute?q=myVal
Note: I would also add ng-model-options="{updateOn:'blur'}" to your input, to prevent updating the URL on every key press.
EXAMPLE
Here is a working example of how to do this: http://plnkr.co/edit/tphqPeJ0dO74Ux7WpXlU?p=preview
Note that, because of the way plnkr.co works, you won't see the URL changes in the address bar on that site. If you download the code and run it locally, the URL would be updated in the address bar.

Hi I found a javascript solution for that.
$scope.gettext = function (search){
window.history.pushState("object or string", "Title", "/angulRoute/search="+search);
};
with <input type="text" class="form-control" ng-model="search" ng-change="gettext(search)" > worked for me. However anyone have an AngulerJs solution they are welcome :D

Related

angularjs stops working whenever I name the ngapp or try using a controller

I am starting to learn AngularJS and wanted to try building a simple calculator app, however, whenever I name the ng-app in my html-file, AngularJS stops working.
I tried building a controller, but seem to be doing something wrong when calling it or putting it to use.
I tried putting the files in the XAMPP webfolder because I thought it might not load from my hard drive, but to no avail.
(please disregard all the half-finished rest, right now I just want to get the controller working)
Here is the html:
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body ng-app="calculatorApp">
<div ng-controller="mainCtrl">
<input type="number" ng-model="first" autofocus>
<input type="number" ng-model="second">
<br>
<button onClick="defineOperator('+')">+</button>
<button onClick="defineOperator('-')">-</button>
<button onClick="test()">TEST</button>
<br>
<div>
{{first}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"</script>
<script src="http://localhost/calculator/scripts/app.js" type="text/javascript"></script>
</body>
</html>
And the js:
angular.module('calculatorApp', [])
.controller('mainCtrl', function($scope){
$scope.defineOperator = function(choice) {
switch (operator) {
case +:
return first + second;
break;
default:
}
};
$scope.testOperator = function(click) {
alert("You chose " + operator);
};
});
Any help would be greatly appreciated.
angular.module('calculatorApp', [])
.controller('mainCtrl', function($scope){
$scope.first="hello";
});
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body ng-app="calculatorApp">
<div ng-controller="mainCtrl">
<div>
{{first}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</body>
</html>
Have a look at this. One thing you have not closed the tag in which angular is defined.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"</script>
You forgot to put > in above line.
Replace it with
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
You forgot to end the script tag with >
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"</script>
if you want to change the app-name in html page you should also change the app name in the js file :
angular.module('calculatorApp', [])

How to get data from JSON using Angularjs?

var app = angular.module("app", []);
app.controller('emp', ['$scope', 'empService', function($scope, empService){
$scope.doSearch = function(){
empService.findEmployeeById($scope.searchempno, function(r){
$scope.empno = r.empno;
$scope.ename = r.ename;
$scope.salary = r.salary;
$scope.dptno = r.dptno;
});
};
}]);
app.service('empService', ['$http', '$log', function($http, $log){
this.findEmployeeById = function(empno, cb){
$http({
url: 'employees.json' + empno,
method: 'GET'
}).then(function(resp){
cb(resp.data);
});
};
}]);
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="app">
<div ng-controller="emp">
<form class="form-inline">
<div class="form-group">
<label>Enter Employee Number:</label>
<input type="text" class="form-control" ng-model="searchEmpno"/>
</div>
<button class="btn btn-primary" ng-click="doSearch()">Search</button>
</form>
<hr>
<div class="row">
<div class="col-sm-2">Employee No</div>
<div class="col-sm-2">{{empno}}</div>
</div>
<div class="row">
<div class="col-sm-2">Employee Name</div>
<div class="col-sm-2">{{ename}}</div>
</div>
<div class="row">
<div class="col-sm-2">Salary</div>
<div class="col-sm-2">{{salary}}</div>
</div>
<div class="row">
<div class="col-sm-2">Deptno</div>
<div class="col-sm-2">{{dptno}}</div>
</div>
</div>
</body>
</html>
If I gave the number in input field like 1001 and click the search button. It will not show the details. I have checked the console, there is no error. My JSON file has been placed the same location of the HTML file.
Thanks,
SamBhishma
I have created an updated plunker here. First issue was what I mentioned in the comment. In your view, you are writing <input type="text" class="form-control" ng-model="searchEmpno"/>and in your controller, you're trying to access this variable as searchempno
Second issue is in your http request. You cannot pick and choose the data from json file based on the id. You have to get the entire JSON file, parse it and filter out the value if it matches your searchEmpno model value. I fixed it in the plunker.
Third issue, you are attaching plain values to your scope like $scope.empno , $scope.ename. Instead, you need to put such values into an object, so in your controller, put the matched employee object in the scope and in your view, reference it as {{obj.ename}} and so on.
Another thing, no need to return callbacks inside then. The clean way of handling successful, failed http calls is:
$http.get('url').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Read more about them here.
Take a look at the updated plunker to see if it matches your needs.
Problem is your model variable is wrong inside the view, try this
<input type="text" class="form-control" ng-model="searchEmpno"/>
DEMO

AngularJS - Save text input by user and displaying it in a different page

I have a input text like in one page. I would like to store the information from this input with angular, so when moving to another page I could display it in another input text.
I have tried with ng-model and ng-init
<input type="text" ng-model="inputText" ng-init="userText">
Having in the controller
$scope.userText = $scope.inputText;
But it doesn't seem to work. You can see a working plunker here. Thanks in advance!
PS: I need to do it between two pages (not with a single page and then routing).
basically what happens is that your variables are reseted when you change page. You can achieve what you want using localstorage. Here follows an example
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.saved = localStorage.getItem('userText');
$scope.userText = (localStorage.getItem('userText')!==null) ? $scope.saved : "";
$scope.editText = function(){
localStorage.setItem('userText', $scope.userText);
}
});
PAGE 1:
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
Home
Another page<br><br><br>
<input type="text" ng-model="userText" ng-keyup="editText()">
</html>
PAGE 2:
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
Home
Another page<br><br><br>
<input type="text" ng-model="userText" ng-keyup="editText()">
<h1>This is Another Page!</h1>
</body>
</html>
please check this plunker: http://plnkr.co/edit/eyywQGgWjhC8gS7Wprcw?p=preview
You can store in rootscope/ localstorage/ URL as parameter . The retrieve value on your destination page

Why does this code break once "app" and the ng-controller are added?

This code is virtually verbatim from egghead.io, but it is not working at all unless I remove ="app" and remove the ng-controller attribute from the <body> element. (And of course the last <script> element gets ignored in the process—the code that would normally be in app.js.) Of course removing those bits prevents anything else from working or being added.
<!doctype html>
<html ng-app="app">
<head>
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<script src="http://code.angularjs.org/angular-ui-router-1.0.0.min.js"></script>
<script>
angular.module('app', ['ui.router'])
.controller("FirstCtrl", function FirstCtrl() {
var first = this;
first.greeting = "First";
});
</script>
</head>
<body ng-controller="FirstCtrl as first">
<div>
<input type="text" ng-model="first.greeting" placeholder="First Name">
<hr>
<h1>{{ first.greeting }} World!</h1>
</div>
</body>
</html>
Here's similar code on JSFiddle. (It's only similar because JSFiddle imposes constraints that make it impossible to post identical code. It has the same problem, so I assume the differences are insignificant for tracking down the source of the bug.)
Where is the bug? Why is this not working?
With latest angular dependency it worked for me.
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script>
angular.module('app', ['ui.router'])
.controller("FirstCtrl", function FirstCtrl() {
var first = this;
first.greeting = "First";
});
</script>
</head>
<body ng-controller="FirstCtrl as first">
<div>
<input type="text" ng-model="first.greeting" placeholder="First Name">
<hr>
<h1>{{ first.greeting }} World!</h1>
</div>
</body>
</html>
You are using angular ui-router but not using it the way you are supposed to be. Check the documentation here to get a clearer idea. Angular UI router loads its contents in a container containing ui-view attribute. As per documentation
AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in Angular core, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.
You need to load different states in your ui-view and also pass values in different states in the process. You need to add dependencies for $stateProvider and $urlRouterProvider in your app config for a completely functional angular ui router implementation. This being told what you need to do is like below -
And also check out the working example in PLUNKER
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>AngularJS: UI-Router Quick Start</title>
<!-- Bootstrap CSS -->
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container">
<div class="row">
<div class="span12">
<div class="well" ui-view></div>
</div>
</div>
<!-- Angular -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></script>
<!-- UI-Router -->
<script src="//angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
<!-- App Script -->
<script>
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/route1")
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html",
controller: function($scope) {
$scope.greeting = "First";
}
})
})
</script>
</body>
</html>

How to access default input value from controller

Input field contains JSON data set from some other script.I have to access in controller.How can I access it in controller.Code I am using something like this-
<html>
<head>
<title>Angular JS Controller</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="" ng-controller="studentController">
Enter first name: <input class="get" type="text" ng-model="student">
</div>
<script>
function studentController($scope) {
console.log($scope.student);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
With Angular, the controller is who tells the View what the default value should be (not the other way around). The View would reflect that, and could update it (with ng-model), but it is initially set by the controller.
So, the controller knows because the controller sets it up:
.controller("studentController", function($scope){
$scope.student = "default name";
});

Resources