I am learning AngularJS and I finally got something to work (I implemented a search feature )
Now, I am trying to build a menu based on my search code in AngularJS.
everything works BUT I have to repeat the same code over and over:
ng-model="searchText" ng-click="search('link-6')"
Here's my code:
<!DOCTYPE html>
<html ng-app="casz">
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<section ng-controller="SearchCtrl">
<nav>
<a href="/link-1/" ng-model="searchText" ng-click="search('link-1')" >link-1</a>
<a href="/test/" ng-model="searchText" ng-click="search('test')" >test</a>
<a href="/link/" ng-model="searchText" ng-click="search('link')" >link</a>
<a href="/link-4/" ng-model="searchText" ng-click="search('link-4')" >link-4</a>
<a href="/stackoverflow/" ng-model="searchText" ng-click="search('stackoverflow')" >stackoverflow</a>
<a href="/link-6/" ng-model="searchText" ng-click="search('link-6')" >link-6</a>
<a href="/link-abc/" ng-model="searchText" ng-click="search('link-abc')" >link-abc</a>
<a href="/link-8/" ng-model="searchText" ng-click="search('link-8')" >link-8</a>
<a href="/zzz/" ng-model="searchText" ng-click="search('zzz-9')" >zzz</a>
</nav>
<article ng-repeat="d in data">
<h3>{{d.title}}</h3>
<p>{{d.description}}</p>
</article>
</section>
<!-- JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('casz',[]);
app.controller("SearchCtrl", function($scope, $http) {
$scope.search = function(p) {
$http({
cache: false,
dataType: 'json',
url: '/getdata.php?',
method: "POST",
data: 'title=' + p,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.status = status;
$scope.data = data;
}).error(function (data, status, headers, config) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
});
</script>
</body>
</html>
Is there a way to NOT repeat this code "ng-model="searchText" ng-click="search('link-6')" and use data- or something like that?
=== i edited my question ===
You can create an array of links and show them separately via ng-repeat
<a ng-repeat="link in links"
ng-href="/link-{{link}}/"
ng-model="searchText"
ng-click="search('link-' + link)" >
link-{{link}}</a>
Example Plnkr
Related
I am trying to add userName use AngularJs into Sharepoint. Also, i should have a feature that I should view all the userName from SharePoint list. But i keeping getting error says '_spPageContextInfo is not defined'.
I am just start learning SharePoint and AngularJs. Can someone help me with it? Thank you.
Here is the code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<!-- modules -->
<script src="app.js"></script>
<!-- controllers -->
<script src="view.js"></script>
<script src="add.js"></script>
</head>
<body ng-app="myApp">
<h3>view</h3>
<div class="view" ng-controller="viewItemsController" ng-repeat="user in users">
<!-- {{user.ID}}: -->
{{user.Title}}, {{user.FirstName}},{{user.LastName}}
<br />
</div>
<hr>
<h3>add</h3>
<div class="add" ng-controller="addItemsController">
<div class="Table">
<div class="Row">
<div class="Cell">Title :</div>
<div class="Cell">
<input type="text" id="title" ng-model="title" />
</div>
</div>
<div class="Row">
<div class="Cell">First Name :</div>
<div class="Cell">
<input type="text" id="firstName" ng-model="firstName" />
</div>
</div>
<div class="Row">
<div class="Cell">Last Name :</div>
<div class="Cell">
<input type="text" id="lastName" ng-model="lastName" />
</div>
</div>
<div class="Row">
<div class="Cell"></div>
<div class="Cell">
<input type="button" id="btnAddContact" value="Add Name" ng-click="addContact()" />
</div>
</div>
</div>
</div>
</body>
</html>
app.js //this is module
var spApp = angular.module('myApp',[]);
view.js // first controller
spApp.controller("viewItemsController", function ($scope, $http) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Users')/items?$select=Title,First_Name,Last_Name";
$http(
{
method: "GET",
url: url,
headers: { "accept": "application/json;odata=verbose" }
}
).success(function (data, status, headers, config) {
console.log(data);
$scope.users = data.d.results;
}).error(function (data, status, headers, config) {
});
});
add.js // second controller
spApp.controller("addItemsController",function($scope,$http){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Users')/items";
var vm = $scope;
vm.addContact = function () {
return $http({
headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": jQuery("#__REQUESTDIGEST").val() },
method: "POST",
url: url,
data: {
'Title': vm.title,
'First_Name': vm.firstName,
'Last_Name':vm.lastName
}
})
.then(saveContact)
.catch(function (message) {
console.log("addContact() error: " + message);
});
function saveContact(data, status, headers, config) {
alert("User Added Successfully");
return data.data.d;
}
}
});
EDIT:
After check this, I am able to run my app now. Help this link could help other people.
It is not obvious, to me at least, what you are doing with index.html.
_spPageContextInfo will only be available on a SharePoint hosted page (i.e. script editor webpage, page layout, sharepoint designer edited page).
It will only be available once SP.js has excuted (See SharePoint scripts on demand).
If you are trying to do proper best practise sharepoint web development then look into SharePoint SPFX
I hope this is helpful
I'm trying AngularJS for the first time. I'm getting as imple user JSON data from a http-get request, but the object is returned null. I tested my service using chrome and I get this result:
[{"id":1,"email":"walid#gmail.com","name":"walid"}]
Below my js file:
var app = angular.module("userApp", []);
app.controller("userController", function($scope, $http) {
$scope.user = null;
$scope.name = null;
$scope.getUser = function() {
$http({
method : 'GET',
url : '/all',
}).success(function(data) {
$scope.user = json.stringify(data);
}).error(function(data) {
alert('Fail: user is '+data);
});
}
});
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SIM Card</title>
<link rel="Stylesheet" type="text/css"
href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="Stylesheet" type="text/css" href="css/simcard.css">
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="js/simcard2.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
</head>
<body ng-app="userApp" ng-controller="userController">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info spacer">
<div class="panel-heading">User Management</div>
<div class="panel-body">
<form action="">
<div class="form-group">
<label>ID</label> <input type="text" ng-model="email">
<button ng-click="getUser()" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info spacer">
<div class="panel-heading">Result</div>
<div class="panel-body">
<div class="form-group">
<label>Name: </label>
<label>{{user.name}}</label>
</div>
</div>
</div>
</div>
</body>
</html>
I can send the whole maven project in case needed. Thank you for your help.
Regards,
Walid
you can do it like this:
var app = angular.module("userApp", []);
app.controller("userController", function($scope, $http) {
$scope.getUser = function() {
return $http.get('/all').then(
function successCallback(response) {
// you can log response here to see what it is
// or you can simply check network in your browser DevTools
$scope.users = response;
},
function errorCallback(response) {
alert('There was error retrieving users List');
}
);
};
});
once that is done based on your response which is an array you can repeat it in your view. ngRepeat is also watching your model update so every time you update $scope.users it will update itself.
So you can simply use this in your view:
<div ng-app="userApp" ng-controller="userController">
<ul>
<li ng-repeat="user in users">
<span> {{user.id}} {{user.name}} {{user.email}} </span>
</li>
</ul>
</div>
The benefit of using $http.get(...).then() is that you can you can use promise chain with ease to build other services on top of this. In your case you have to make sure that you check your response.
// Update :
Here's a Bin that you can see the code above in action: https://jsbin.com/luguzu/1/edit
Just in output hit Run with js and click Get Users.
The problem is in your config of the request:
http://plnkr.co/edit/qEkpUAXQQZmO9iUAZ2aX?p=preview
It doesn't know what type of data you expect in response.
Your http request should look like this:
$http.get("test.json").success(function(data) {
$scope.user = data[0];
}).error(function(data) {
alert('Fail: user is 2 '+data);
});
Update:
Just noticed something in yout HTML - you have there a form with action empty. This is the cause of the request being canceled.
in angularjs to have a form, it is enought to add to a div ng-form="myForm" and the input can be just simple button, not submit and it is going to work fine.
Here it is the image of my network console...
I have been having this issue with Controllers in Angular. I looked it up as much as possible, but I could not resolve the issue.
I am trying to implement a simple controller, but for the life of me, I cannot get the binding to work. It's not displaying my data. For example when I say, {{ test }}, I get just that, not the "Hello World!" string.
var app = angular.module('App', []);
app.controller('Hi', function($scope){
$scope.hello = "hello!";
});
app.controller('todoCtrl', ['$scope', '$http', function($scope, $http) {
$scope.test = "Hello World!";
$scope.formData = "";
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$scope.formData.text = "";
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
<!DOCTYPE html>
<html ng-app="App">
<head>
<title>TodoX</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!-- TodoX CSS -->
<link rel="stylesheet" type="text/css" href="stylesheets/style.css"/>
</head>
<body ng-controller="todoCtrl">
<div class="container">
<div class="row">
<div class="jumbotron text-center">
<h1>TodoX<span>{{todos.length}}</span>{{test}}</h1>
</div>
<div class="col-md-8">
<div class="list-group">
<div class="checkbox" ng-repeat="todo in todos | orderBy:date">
<label class="list-group-item">
<input type="checkbox"/> {{todo.text}}
</label>
</div>
</div>
</div>
<div class="col-md-4">
<form class="form-group">
<input type="text" class="form-control" ng-model="formData"/>
<input type="submit" ng-click="createTodo()" placeholder="Submit" class="form-control"/>
</form>
</div>
</div>
</div>
<!-- Angular JS -->
<script type="text/javascript" href="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<!-- TodoX Core JS -->
<script type="text/javascript" href="core.js"></script>
</body>
</html>
I just executed your code while placing angular file link above the script tag, so that AngularJs is loaded before your script can call angular modules.
I think you're putting angular after your script which is why you are running into this issue. Your code works just fine. I tested it.
Put it like this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="script.js"></script>
Here script.js will be your controller script.
Working fiddle
I hope you may help me.
I'm quite new with Angular so I'm maybe making some stupid error but, when a give a value to ng-app, it doesn't work AngularJs.
I make here an example:
This is my home.html that doesn't work (when I say "doesn't work" I mean that I see printed "{{name}}" instead of its value).
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
data: {"nome":$scope.name}
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
$http(req).success(function(data, status, headers, config) {
$scope.nome = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app="noteApp">
<div ng-controller="noteCtrl">
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
but if I change it like this
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
data: {"nome":$scope.name}
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
$http(req).success(function(data, status, headers, config) {
$scope.nome = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app>
<div>
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
it goes perfectly as it should.
Any suggestion?
In your view you are using {{ name }} but inside of your controller you are putting the data inside of $scope.nome.
Just change $scope.nome > $scope.name
You are setting the req variable using $scope.name but at that point scope is not defined. If you open the console you will see an error about. Try this:
http://plnkr.co/edit/LqZNX8BYnCnbUD29YRfi?p=preview
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
req.data={"nome":$scope.name};
$http(req).success(function(data, status, headers, config) {
$scope.name = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app="noteApp">
<div ng-controller="noteCtrl">
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
the wrong variable name ("nome" instead of "name") is unrelated to your issue but it still need to be corrected
You are missing a " ; " after "var app=angular.module('noteApp', [])" so noteApp is not getting initialized.
I have currently included all service files and controller files in index.html in my angularJS application and it is working fine.
But I want to include the respective service file and controller file in the template file, so that unwanted files for the home page of my application will not be loaded in the initial load: thus decreasing the time to load the home page.
I have tried to do this, but the I could not get the json data from the service.
Here is what I have done so far
app.js
var app = angular.module('app', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/books',
{
templateUrl:'app/templates/books.html',
controller:'booksController'
}).when('/games',
{
templateUrl: 'app/templates/games.html',
controller: 'gamesController'
});
$locationProvider.html5Mode(true);
});
eventData.js service file
app.factory('eventData', function ($http, $log, $q) {
return {
getEvent: function () {
var deferred = $q.defer();
$http({
method: 'GET', url: 'https://www.googleapis.com/books/v1/volumes?q=harry%20potter'
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
},
getGames: function () {
var deferred = $q.defer();
$http({
method: 'GET', url: 'https://www.googleapis.com/books/v1/volumes?q=hunger%20games'
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
eventController.js
'use strict';
app.controller("EventController", function EventController($scope,eventData) {
$scope.event = eventData.getEvent();
$scope.event.then(function(event) {
console.log(event);
$scope.items = event.items;
console.log($scope.items);
},function(status) {
console.log(status);
});
});
BooksController.js
'use strict';
app.controller("booksController", function booksController($scope, eventData) {
$scope.event = eventData.getEvent();
$scope.event.then(function (event) {
console.log(event);
$scope.items = event.items;
console.log($scope.items);
}, function (status) {
console.log(status);
});
});
books.html
<script src="app/controllers/eventController.js"></script>
<script src="app/controllers/booksController.js"></script>
<script src="app/services/eventData.js"></script>
<div style="padding-left: 20px;padding-right: 20px">
<div class="row">
<h3>Sessions</h3>
<ul style="list-style-type: none;">
<li ng-repeat="session in items">
<div class="row session">
<div class="well col-md-12">
<h4 class="well">{{session.volumeInfo.title}}</h4>
<h6 style="margin-top: -10px">{{session.volumeInfo.publishedDate}}</h6>
<span>Page Count: {{session.volumeInfo.pageCount}}</span><br />
<span>Authors: {{session.volumeInfo.authors}}</span>
<p>{{session.searchInfo.textSnippet}}</p>
</div>
</div>
</li>
</ul>
</div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Airlines!</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<meta charset="utf-8">
<base href="/airlines/">
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>Harry Potter</li>
<li>Hunger Games</li>
</ul>
</div>
</div>
<ng-view></ng-view>
</div>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.js"></script>
<script src="app/app.js"></script>
</body>
</html>
Can you identify what I am doing wrong?