I need to get the specific id of each line and forward to a JS function that will make an http request. But I'm having trouble calling this function, excluir(id), the parameters are correct but the alert doesn't run. Why is that?
HTML
<!DOCTYPE html>
<html ng-app="oknok">
<head lang="pt-br">
<meta charset="UTF-8"/>
<title>OKNOK Admin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="js/controller.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="indexController" data-ng-init="init()">
<div class="container">
<h2>Listagem de veĆculos</h2>
<table class="table table-condensed">
<thead>
<tr>
<th>Nome</th>
<th>Tipo</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in resultado">
<td ng-model="nome">{{x.nome}}</td>
<td ng-model="tipo">{{x.tipo}}</td>
<td ng-model="lixeira"><span class="glyphicon glyphicon-trash" ng-click="excluir({{x._links.self.href}})"></span></td>
</tr>
</tbody>
</table>
<div align="right">
<button type="button" class="btn btn-primary" ng-click="adicionarNovo()">Adicionar novo</button>
</div>
</div>
</body>
</html>
Controller.js
var oknok = angular.module('oknok', []);
oknok.controller('indexController', function ($scope, $http) {
$scope.init = function () {
$http.get("/api/veiculos")
.then(function (data) {
var embedded = data.data._embedded;
$scope.resultado = embedded.veiculos;
}).catch(function (error) {
alert("Erro ao obter dados!\n" + error);
});
};
$scope.adicionarNovo = function () {
window.location.href = "/cadastro";
};
$scope.excluir = function (id) {
alert("clicou" + "\t" + id);
}
});
The functions don't need {{}} as everybody said before on ng-click remove them.
Like that :
ng-click="excluir(x._links.self.href)"
Try injecting "$window" instead. That way, you'll be sure the window object has the proper angular lifecycle:
var oknok = angular.module('oknok', []);
oknok.controller('indexController', function ($scope, $http, $window) {
$scope.init = function () {
$http.get("/api/veiculos")
.then(function (data) {
var embedded = data.data._embedded;
$scope.resultado = embedded.veiculos;
}).catch(function (error) {
$window.alert("Erro ao obter dados!\n" + error);
});
};
$scope.adicionarNovo = function () {
$window.location.href = "/cadastro";
};
$scope.excluir = function (id) {
$window.alert("clicou" + "\t" + id);
}
});
Related
I would like to call a server-side service when my filter is empty.
this is my HTML:
<html lang="en">
<head>
<meta charset="utf 8">
<title>test angular</title>
</head>
<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<body ng-app="app">
<h1 ng-app="app" ng-controller="HelloWorldCtrl">{{message}}</h1>
<p><input type="text" id="myfilter" ng-model="seachText"></p>
<div ng-app="app" id="search" ng-controller="serviceCall">
<ul>
<li ng-repeat="x in lau | myfilter:seachText">
{{ x.des }}
</li>
</ul>
</div>
and this is my code:
var app = angular.module("app", []);
app.controller("serviceCall", function($scope, $http) {
var v=document.getElementById('search').value;
if (!v){v="Vigo";}
$http.get("http://127.0.0.1/KLAU.pl?search="+v+"&lim=10").then(function(response) {
$scope.lau = response.data;
});
});
app.filter('myfilter', [function($scope){
return function(input, param) {
if(!angular.isDefined(param)) param = '';
var ret = [];
angular.forEach(input, function(v){
var regx=new RegExp(param, 'gi');
if(regx.test(v.des)){
ret.push(v);
console.log("match!!");
}
});
if (!ret.length ){
$scope.serviceCall();
}
return ret;
};
}]);
I'm getting:
typeError: "$scope is undefined".
thanks in advance for the help.
$scope does not work in filter. Better inject a service, or pass the service function as another parameter to the filter:
return function(input, param, serviceCall) {
//...
serviceCall() // replaces $scope.serviceCall();
//...
}
Make sure you define serviceCall in the controller that calls the filter:
app.controller("serviceCall", function($scope, $http) {
var v=document.getElementById('search').value;
if (!v){v="Vigo";}
$scope.serviceCall = function() {
$http.get("http://127.0.0.1/KLAU.pl?search="+v+"&lim=10").then(function(response) {
$scope.lau = response.data;
});
};
$scope.serviceCall();
});
});
In HTML:
<li ng-repeat="x in lau | myfilter:seachText:serviceCall">
I follow the "AngularJS: Get Started" course from Plualsight, and I reach the Routing module, so I have some files in Plunker, on the course they can see on Preview page the title which is "Github Viewer" and a search bar. But I still get errors in console, and I do not know why, my code should be identical as their code.
So I have the following files :
app.js
(function() {
var app = angular.module('githubViewer', ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo: "/main"});
});
}());
github.js
(function() {
var github = function($http) {
var getUser = function(username) {
return $http.get("https://api.github.com/users/" + username)
.then(function(response) {
return response.data;
});
};
var getRepo = function(user) {
return $http.get(user.repos_url)
.then(function(response) {
return response.data;
});
};
return {
getUser : getUser,
getRepo : getRepo
};
};
var module = angular.module("githubViewer");
module.factory("github", github);
}());
index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.3.14" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script scr="app.js"></script>
<script src="MainController.js"></script>
<script src="github.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view></div>
</body>
</html>
main.html
<div>
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
MainController.js
// Code goes here
(function() {
var app = angular.module("githubViewer");
var MainController = function($scope, $interval, $location) {
console.log("Atentie!")
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
//
};
$scope.username = "Angular";
$scope.countdown = 5;
startCountdown();
};
app.controller("MainController", MainController);
}());
userdetails.html
<div id="userDetails">
<h2>{{user.name}}</h2>
<img ng-src="{{user.avatar_url}}" title="{{user.name}}">
<div>
Order:
</div>
<select ng-model="repoSortOrder">
<option value="+name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="+language">Language</option>
</select>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Stars</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | limitTo:10 | orderBy:repoSortOrder">
<td>{{repo.name}}</td>
<td>{{repo.stargazers_count | number }}</td>
<td>{{repo.language}}</td>
</tr>
</tbody>
</table>
And the style.css which is empty.
So at this point I should see in a separete window something like in the following picture and no errors in console.
But I se only the title, like in the following picture
and errors
Could someone help me to understand why isnt' work ?
Was some changes in AngularJS and the course isn't up to date ?
You made a typo
<script scr="app.js"></script>
should be
<script src="app.js"></script>
Also make sure that when using angularjs core api's, all the API should be off same version. Here you're using angularjs (ver. 1.3.12) & angular-route (ver. 1.6.2)
Change both to 1.6.2 or latest
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
Demo Here
here we go...
I have a controller
$scope.selectedScript = {};
$scope.selectedScript.scriptId = null;
$scope.selectScript = function(script, index) {
$scope.selectedScript = script;
$scope.selectedRow = index;
myAppFactory.updateTextArea(script).success(
function(data) {
$scope.selectedScript = data;
});
};
$scope.getSelectedClass = function(script) {
if ($scope.selectedScript.scriptId != undefined) {
if ($scope.selectedScript.scriptId == script.scriptId) {
return "selected";
}
}
return "";
};
i have a html page
<label>Script ID:</label>
<input name="scriptId"
type="text"
id="scriptId"
ng-model="selectedScript.scriptId"
ng-disabled="true"
value="{{selectedScript.scriptId}}" />
and now thx to IARKI i have this
<script type="text/javascript">
function goTo (){
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
Debug
I have also a list of scripts in a table
<table class="scripts" name="tableScript" arrow-selector>
<tr bgcolor="lightgrey">
<th>Script ID</th>
<th>File Name</th>
</tr>
<tr
ng-repeat="s in scripts | filter:searchField | orderBy:'scriptId'"
ng-click="selectScript(s, $index)" ng-class="getSelectedClass(s)">
<td>{{s.scriptId }}</td>
<td>{{s.fileName }}</td>
</tr>
</table>
Then i press the link above, and a new tab appears, but the link is still the
http://localhost:8080/DSS-war/debug.html
but i need it to open in a new tab as well as to be like this:
http://localhost:8080/DSS-war/debug.html?scriptId=1
http://localhost:8080/DSS-war/debug.html?scriptId=2
http://localhost:8080/DSS-war/debug.html?scriptId=12
and so on...with numbers
any idea?
And it has to be the onclick function, not the ng-click
I know how it works on ng-click, but i need to make it work on onclick...
and now i get this from the chrome debugger:
Uncaught TypeError: Cannot read property 'scriptId' of undefined
in the line
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
You can try to access angular scope using pure javascript
<script type="text/javascript">
function goTo (){
var param1 = angular.element("#scriptId").scope().selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
Debug
Update
Useless code but I hope it will help you
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My application</title>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<label>Script ID:</label>
<input name="scriptId" type="text" id="scriptId" ng-model="selectedScript.scriptId" ng-disabled="true">
<button onclick="generateID()">Set code</button>
Debug
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript">
function generateID() {
var code = Math.floor(Math.random() * 20) + 1;
document.getElementById('scriptId').setAttribute('value', code.toString());
}
function goTo() {
var scope = angular.element(document.querySelector('#scriptId')).scope();
scope.$apply(function () {
scope.selectedScript.scriptId = document.querySelector('#scriptId').getAttribute('value');
});
scope.changeURl();
}
angular.module('myApp', [])
.controller('myCtrl', function ($scope, $window) {
$scope.selectedScript = {};
console.log('We are in controller');
$scope.changeURl = function () {
$window.open('http://localhost:8080/DSS-war/debug.html?scriptId=' + $scope.selectedScript.scriptId, '_blank');
}
});
</script>
</html>
I am writing code in Angular JS implement a standard application which would show a search field and a search button the screen and when a search is run, it should pull in the remote result and display them on the screen
Console is not showing any errors to me but i cant get to display the results on the screen.I am wondering how do i display the results on the screen
here is the code in my js file
angular.module('plunker', [])
.controller('MainCtrl', ['$scope', '$http',
function($scope, $http) {
var clearError = function(result) {
$scope.error = "";
return result;
};
var applyData = function(result) {
$scope.articles = result.data;
console.log(result.data);
};
var rejected = function(error) {
$scope.error = error.message;
};
var getArticles = function() {
var url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=North+Korea&api-key=052861d142cf4eb7fa12bb79781fdbe1:11:69591426";
var promise = $http({
method: 'GET',
// https://jsonp.nodejitsu.com
url: "https://jsonp.nodejitsu.com/?url=" + encodeURIComponent(url)
});
promise.success(clearError).then(applyData);
promise.error(function(error) {
$scope.error = error.message;
});
};
getArticles();
$scope.getRepos = _.debounce(getArticles, 300);
}]);
And here is the html code
<!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="lodash.js#*" data-semver="2.4.1" src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<input ng-keyup="getArticles()" />
<table>
<thead>
<tr>
<td>Headline</td>
<td>Body</td>
</tr>
</thead>
<tbody>
<tr ng-bind="error" style="color:red;"></tr>
<tr ng-repeat="a in Articles">
<td>{{a.headline}}</td>
<td>{{a.body}}</td>
</tr>
</tbody>
</table>
</body>
</html>
You have several issues.
In scope you have articles but in html it is Articles.
To access the actual data you want in response you need to look deeper inside the data object returned:
Try changing:
var applyData = function(result) {
$scope.articles = result.data;
console.log(result.data);
};
To:
var applyData = function(result) {
var articles=result.data.response.docs
$scope.articles = articles;
console.log(articles);
};
Then in the html you need slightly different properties since headline has sub properties like main and print_headline
As example
<tr ng-repeat="a in articles">
<td>{{a.headline.main}}</td>
<td>{{a.lead_paragraph}}</td>
</tr>
DEMO
I'm new to AngularJS and I'm trying to make a home page that loads dynamic content from my database to create links. When I click one of those links on the home page, it sends a request to my node server and retrieves the appropriate data from the database and displays that on the partial view. When I'm on that partial view and I click the browser's back button to go back to the home page, the dynamic content that was originally loaded doesn't display. Below is my code. Why doesn't clicking the browser's back button redisplay the home page with the dynamic content?
index.html
<!doctype html>
<html lang="en" ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>My site</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/animations.css">
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="/js/animations.js"></script>
<script src="/js/controllers.js"></script>
<script src="/js/filters.js"></script>
<script src="/js/app.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/" ng-click="home()">Home</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" data-provide="typeahead" autocomplete="off" placeholder="foo, bar" ng-model="query">
</div>
</form>
<ul class="nav navbar-nav navbar-right">
</ul>
</div>
</div>
</nav>
</div>
<div class="view-container">
<div ng-view class="view-frame"></div>
</div>
</body>
</html>
phone-detail.html
<div class="phone-images">
<img ng-src="{{thing.imageUrl}}" dclass="phone">
</div>
<h1> {{ things[0].name }} </h1>
<iframe id="viddy" width="560" height="315" ng-src="{{ things[0].embed }}" frameborder="0" allowfullscreen autoplay="1" ></iframe>
<p>source:</p>
<p>{{ things[0].vid }}</p>
</div>
phone-list.html
<div class="container-fluid">
<div class="row">
<div class="col-md-10">
<!--Body content-->
<div>
<div ng-if="things.length>1">
<ul class="phones">
<li ng-repeat="foo in things | filter:query"
class="thumbnail phone-listing">
<img ng-src="{{foo.imageUrl}}">
{{foo.name}}
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
//controller.js
'use strict';
/* Controllers */
var coreControl = angular.module('prjController', []);
coreControl.controller('mainController', ['$scope', '$http', '$sce', '$locationProvider'
function($scope, $http, $sce, $locationProvider)
{
//$scope.$on('$routeChangeSuccess', function(req, res) {console.log($route.current.params);})
$scope.formData = {};
$scope.things = [];
$scope.maxThings = 0;
$http.get('/things')
.success(function(data)
{
$scope.things = data;
$scope.maxThings = $scope.things.length;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
$scope.home = function()
{
$http.get('/things')
.success(function(data)
{
$scope.things = data;
$scope.maxThings = $scope.things.length;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
}
$scope.search = function(thing)
{
$http.get('/thing/'+thing, $scope.formData)
.success(function(data)
{
$scope.formData = {};
$scope.things = data;
$scope.msg = "Recommend a video."
$scope.noMatch = false;
if($scope.things.length == 0)
{
$scope.noMatch = true;
}
$scope.things[0].embed = $sce.trustAsResourceUrl($scope.things[0].embed+"?autoplay=0&showinfo=0&controls=0&loop=1");
document.getElementById('viddy').src = document.getElementById('viddy').src;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
}
}]);
//app.js
'use strict';
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatAnimations',
'prjController'
]);
phonecatApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/:thingId', {
templateUrl: 'partials/phone-detail.html'
}).
otherwise({
templateUrl: 'partials/phone-list.html'
});
}]);
//server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var port = process.env.PORT || 8887;
var db = require('./config/db');
var connection = mysql.createConnection(db);
connection.connect();
app.configure(function()
{
app.use(express.static(__dirname + '/public'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
require('./app/router')(app, connection);
app.listen(port);
exports = module.exports = app;
//router.js
module.exports = function(app, conn)
{
app.get('*', function(req, res){
var url = req.originalUrl;
if(url.match(/^\/thing\/.+/))
{
var query_thing = url.replace(/%20/g, ' ');
query_thing = query_thing.replace(/\/thing\//, '');
require('./search')(query_thing, res, conn);
}
else
{
require('./populate')(res, conn);
}
});
};
//populate.js
module.exports = function(res, connection)
{
function getRandIds(rep, max)
{
var ids = [];
//create a list of rep-many random integers, which may have repetitions
for (var i = 0; i < rep; i++)
{
ids.push(Math.floor(Math.random()*100) % max);
}
function numercalSort(a,b)
{
return a-b;
}
//sort() without the callback sorts alphabetically
ids.sort(numercalSort);
console.log(ids);
var notUnique = false;
//check that each id is unique so that the exact number of ids will be queried
for(var i = 0; i < ids.length; i++)
{
if(i+1 < ids.length && ids[i] == ids[i+1])
{
notUnique = true;
}
}
//recurse if the values are not all unique
if(notUnique)
{
ids = getRandIds(rep, max);
}
return ids;
}
//creates a query that searches for random ids
function queryRand(rep, max)
{
var sql = "select m.name, m.imageUrl, v.vid, v.embed from things as m, videos as v where m.id=v.id and (";
var ids = getRandIds(rep, max);
for(var i = 0; i < ids.length; i++)
{
sql += " m.id like "+ids[i];
if(i < ids.length - 1)
{
sql += " or";
}
else
{
sql += ");";
}
}
var sql = "select m.name, m.imageUrl, v.vid, v.embed from things as m, videos as v where m.id=v.id";
return sql;
}
//handles the output
function handleOut(err, result, fields)
{
if(err) throw err;
console.log('rand results: ',result);
res.json(result);
}
var repetitions = 10; //number of things to display
var totalCount = 372; // total number of things in the database
var sql = queryRand(repetitions, totalCount);
connection.query(sql, handleOut);
};
So after a long while, I finally realized that the issue was that I only had one controller that held the functionality for all my controllers. That was only loading once. Because it only loaded once, the $http.get('/things') call was only being made that once when the controller initially loaded. To resolve this, I separated out my controllers. I made one specifically for my home page, and made a separate partial for it and placed the controller specifically in that partial, so it loads every time the partial loads.
This also required updating the index.html and app.js, appropriately.
//mainController.js
angular.module('prjController', [])
.controller('mainController', ['$scope', '$http', '$sce',
function($scope, $http, $sce)
{
$http.get('/things')
.success(function(data)
{
$scope.things = data;
$scope.maxThings = $scope.things.length;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
}]);
<!-- main.html partial -->
<div class="container-fluid" ng-controller="mainController">
<!--Body content-->
...
</div>