$ng-resource doesn't work? - angularjs

I'm new to AngularJS, I would like to update my data.json but that I don't know where my file users.json should be and I have this error:
Error: $injector:modulerr
http://errors.angularjs.org/1.3.14/$injector/modulerr?p0
Heres my code :
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', ['ngResource']);
app.factory('User', ['$resource',
function($resource){
return $resource('/users/:userId', {userId:'#id'},
{
'update': {method: 'PUT'}
}
);
}
]);
app.controller('UsersCtrl', function ($scope, User) {
$scope.users = User.query();
$scope.validate=function(user) {
user.$update();
}
$scope.delete=function(user) {
user.$delete();
}
$scope.create = function (newUserName) {
var user = new User();
user.name = newUserName;
user.$save();
$scope.users.push(user);
}
});
</script>
<body ng-app="myApp" ng-controller="UsersCtrl">
<ul>
<li ng-repeat="user in users">
<input type="text" ng-model="user.name" />
<button ng-click="validate(user)">Valider</button>
<button ng-click="delete(user)">Supprimer</button>
</li>
</ul>
Nouveau utilisateur :
<input type="text" ng-model="newUserName" />
<button ng-click="create(newUserName)">Créer</button>
</body>
</html>
Anyone have an idea please?

You forgot to add the ngResource file.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
From ngResource page:
You can download this file from the following places:
Google CDN
e.g. //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-resource.js
Bower
e.g. bower install angular-resource#X.Y.Z
code.angularjs.org
e.g. "//code.angularjs.org/X.Y.Z/angular-resource.js" where X.Y.Z
is the AngularJS version you are running.

Working Fiddle: http://jsfiddle.net/softvar/rq9eupee/1/
Add angular-resource script below the angular.js file depending upon the version you need within head tag.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
If you want to read some data from the file users.json, have it on server(Backend) and populate it as per your requirements. If you simply want to show the list of users, fetch it from server, server will read the file and returns it contents. If for some purpose, you need to read the file and display it contents on front-end, have it inside your js/ folder. But assuming, you read it to send the response, it should be on backend.

Related

Setting a cookie in AJAX request with AngularJS

I am trying to set a cookie containing a token value retrieved from an Ajax request in AngularJS.
At first, I tested the result of the request by simply displaying the token value in my html page -> {{myToken}}. The result was correct. Now, I am trying to store that value in a cookie. The lines that I added for that purpose are written between **.
In my HTML page, I imported angular.min.js (v1.4.8), then angular-cookies.min.js (v1.6.3):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XXX</title>
<link rel="stylesheet" href="assets/css/style.css" media="screen" type="text/css" />
<script src="assets/scripts/angular.min.js"></script>
</head>
<body >
<div ng-app="myApp" ng-controller="LoginCtrl">
<h1>Log-in</h1><br>
<form>
<input type="text" name="user" placeholder="Username" ng-model="login">
<input type="password" name="password" placeholder="Password" ng-model="password">
<input type="submit" name="login" class="login login-submit" value="login" ng-click="myLogin()">
</form>
<div class="login-help">
<a id="button-login" href="#">Register</a> • Forgot Password
</div>
<p>myToken: {{myToken}}</p>
</div>
**<script src="assets/scripts/angular-cookies.min.js"></script>**
<script src="assets/scripts/myApp.js"></script>
<script src="assets/scripts/controllers/loginCtrl.js"></script>
</body>
</html>
myApp.js is quite simple for now:
var app = angular.module('myApp', [**'ngCookies'**]);
loginCtrl.js contains the Ajax request trigger when calling myLogin().
app.controller('LoginCtrl', function($scope, $http**, $cookieStore**) {
$scope.login = "";
$scope.password = "";
$scope.myLogin = function() {
$http({ <request>})
.then(function(response) {
$scope.myToken = <token value>;
**$cookieStore.put('myToken', $scope.myToken);**
})
};
});
My page is stored on WampServer and when I reach it, I get the following error:
"Error: [$injector:unpr] http://errors.angularjs.org/1.4.8/$injector/unpr?p0=%24cookieStoreProvider%20%3C-%20%24cookieStore%20%3C-%20LoginCtrl
See AnguleJS: API : $cookies and How to access cookies in AngularJS?
Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies
app.controller('LoginCtrl', ['$scope', '$http', '$cookies', function($scope, $http, $cookies) {
$scope.login = "";
$scope.password = "";
$scope.myLogin = function() {
$http({ <request>})
.then(function(response) {
$scope.myToken = <token value>;
$cookies.put('myToken', $scope.myToken);
})
};
}]);
$cookieStore.put('myToken', $scope.myToken); is invalid now you need to use
$cookies.put('myToken', $scope.myToken);
Ok, so I made a few noob mistakes. Here's what's now working for me:
By using minified scripts, I needed to map the scopes "Uncaught Error: [$injector:unpr]" with angular after deployment
I needed to declare the same versions of scripts. I am now using angular.min.js and angular-cookies.min.js version 1.6.3 (Index of /1.6.3/)
As both repliers said, $cookieStores was deprecated a long time ago $cookieStore deprecated

trying it integrate prismic prismicio with angular js

Hey people i am trying to integrate prismic io with angular js 1 but it is not working.
I referred to many links to do that but i don't get anything data.
https://github.com/awulder/angular-prismicio
https://gist.github.com/laradevitt/94f7e21eaf6d3441b9475fc8f5201201
http://jsfiddle.net/othermachines/bbv9dzug/
and that's my code :
my code
app.js
// Define the `myApp` module
var app = angular.module('app', ['prismic.io']);
app.config(function(PrismicProvider) {
PrismicProvider.setApiEndpoint('https://myname.prismic.io/api');
PrismicProvider.setAccessToken('i put my access token');
PrismicProvider.setClientId('i used my id');
PrismicProvider.setClientSecret('i put my secret');
PrismicProvider.setLinkResolver(function(ctx, doc) {
return 'detail.html?id=' + doc.id + '&slug=' + doc.slug + ctx.maybeRefParam;
});
});
// Define the `AppCtrl` controller on the `app` module
app.controller('AppCtrl', ['Prismic', function(Prismic) {
var self = this;
Prismic.all().then(function(data) {
self.data = data;
});
}]);
index.html
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://unpkg.com/prismic.io/dist/prismic.io.min.js"></script>
<script src="https://raw.githubusercontent.com/awulder/angular-prismicio/master/dist/angular-prismicio.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppCtrl">
<prismic-html fragment="data.fragment"></prismic-html>
<ul>
<li ng-repeat="item in data">
<span>{{item.slug}}</span>
</li>
</ul>
</body>
</html>
The idea with this Prismic thing is that it has the data on it and they are just providing some code for integration and then we read this json data using angular.
please if anyone used it before will be really nice to help.
thanks

Using AngularJS or how to call rest services from CustomApp

I would like to know if it is possible to add angularjs to the custom app in Rally, or as alternative how to call REST services from a Rally Custom app. Can someone help me with this? Thanks in advance.
Best Regards
Here is an example of making a WS API call from an Angular app from inside Rally's custom page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myapp">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<div ng-controller="MyController" >
<button ng-click="myData.doClick(item, $event)">Send AJAX Request to Rally</button>
<br/>
Data from server: {{myData.fromServer}}
</div>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myData = {};
$scope.myData.doClick = function(item, event) {
var responsePromise = $http.get("https://rally1.rallydev.com/slm/webservice/v2.0/defect");
responsePromise.success(function(data, status, headers, config) {
$scope.myData.fromServer = data.QueryResult.Results[0];
console.log(data);
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
}
} );
</script>
</div>
</body>
</html>
Using external CDN within app is expected to produce Mixed Content error if accessing over http. It works if https is used. Here is the first query result (a defect from my current project) is returned.

AngularFire createUser example not working outside of Firebase website

In an attempt to learn AngularFire, I've been messing around with AngularFire user authentication methods. On the Firebase website, an example is given that, when I plug in my Firebase address in the proper place, works. When I copy and paste the code into Notepad++ and attempt to run it that way, the HTML works, but none of the Javascript does. I added an alert box to the Javascript, and on opening the page, the alert box popped up, but none of the rest of the JS worked. I feel like I'm missing something very obvious. What am I doing wrong?
Thanks for any help!
My code is as follows:
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"> </script>
</head>
<body>
<script>
var app = angular.module("sampleApp", ["firebase"]);
// let's create a re-usable factory that generates the $firebaseAuth instance
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://xxxxx.firebaseio.com/?page=Auth");
return $firebaseAuth(ref);
}
]);
// and use it in our controller
app.controller("SampleCtrl", ["$scope", "Auth",
function($scope, Auth) {
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$createUser({
email: $scope.email,
password: $scope.password
}).then(function(userData) {
$scope.message = "User created with uid: " + userData.uid;
}).catch(function(error) {
$scope.error = error;
});
};
$scope.removeUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$removeUser({
email: $scope.email,
password: $scope.password
}).then(function() {
$scope.message = "User removed";
}).catch(function(error) {
$scope.error = error;
});
};
}
]);
</script>
<div ng-app="sampleApp" ng-controller="SampleCtrl">
Email: <input type="text" ng-model="email">
Password: <input type="text" ng-model="password">
<br><br>
<button ng-click="createUser()">Create User</button>
<br><br>
<button ng-click="removeUser()">Remove User</button>
<p ng-if="message">Message: <strong>{{ message }}</strong></p>
<p ng-if="error">Error: <strong>{{ error }}</strong></p>
</div>
</body>
</html>
I think what has happened is that you have used the ng-app directive twice in your html. If you look at the Angular documentation for ng-app, the first ng-app tag is auto bootstrapped as an application, any additional ng-app have to be manually loaded. Also, you cannot nest applications in a page. When I tried to run your application the SampleCtrl controller is undefined.
I've removed the first ng-app directive and the rest of your code seems to work fine in this plunker I've created.
<!DOCTYPE html>
<!--
ng-app directive is already delclared in the body, removing this one
<html ng-app>
-->
<html>
<head>
...
</head>
<body>
<div ng-app="sampleApp" ng-controller="SampleCtrl">
...
</body>
</html>

Simple HTML AngularJS and Intranet server JSON Returns Nothing?

I have a working test service on our local 2012 server which returns JSON like so:
192.168.1.11:8080/api/values
[{"ID":1,"Name":"sankar","Address":"cuttack","DOB":"1983-01-22T00:00:00"},{"ID":3,"Name":"My Test Name","Address":"My Test Address","DOB":"1980-01-01T00:00:00"}]
I'm using VS2010 and empty asp.net project (one .html page) with the following code to pull a simple list from the local server like so:
<html lang="en" data-ng-app="">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
<script type="text/javascript">
function ValuesController($scope, $http) {
$scope.length = 0;
$scope.data = [];
$http.get("192.168.1.11:8080/api/values")
.then(
function (result) {
angular.copy(result.data, $scope.data);
},
function () {
//handle error
}
);
}
</script>
</head>
<body>
<div data-ng-controller="ValuesController">
<div class="row">
<h2>Projects and its Tasks</h2>
<p>Number of Projects : {{ data.length }}</p>
</div>
<div data-ng-repeat="d in data">
<p>Name : {{d.Name}}</p>
</div>
</div>
</body>
</html>
Try adding the protocol to your URL. I think angular might be treating that as a relative URL without the protocol.
$http.get("http://192.168.1.11:8080/api/values")
You will also need to enable CORS on your Web API and in AngularJS to make cross domain calls.
If you are just getting started and trying to learn how AngularJS works, you would probably be better off running the Web API under the same site that is hosting your JavaScript/HTML.

Resources