I am getting an unknown provider error. My structure is set up with two different files, a controller file and a service file. For some reason the angular app cannot find the service? If I put the service within the same file it works fine?
controller file:
(function() {
'use strict'
angular
.module('poke', ['ngResource'])
.controller("appController", appController)
appController.$inject = ['$scope', 'user']
function appController($scope, user){
$scope.saveUser = saveUser;
// getProducts();
//
function saveUser(user_email) {
return user.save({user_email}, function(data) {
$scope.email = []
});
}
}
})()
service file
(function() {
angular
.module('poke')
.factory("user", user)
user.$inject = ['$resource']
function user($resource) {
return $resource("/users",{}, {})
}
})();
html
<body ng-app="poke" ng-controller="appController" ng-cloak>
<div class="page-header">
<h1>Pokemon Go!</h1>
</div>
<form ng-submit="saveUser(email)" style="margin-top:30px;">
<h3>Please enter your email address to receive news about Pokemon Go in your city!</h3>
<input type="text" class="form-control" placeholder="example#email.com" ng-model="email"></input>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
Keep your main Module independently by injecting the global Dependencies. So you no need to refer this dependency in all files.
angular.module('myModule', ['ngResource']);
angular
.module('poke')
.controller("appController", appController)
then you can use $resource dependency across your angular components
Hope this helps
Related
For some reason my controller doesn't seem to be registered and I'm honestly not sure why...
I've been following along an AngularJS and Django development course on PluralSight. The only difference between the instructor's stack and mine is that I'm using Angular 1.6.4 and he is using 1.5.0. I've previously hit some errors (like routing syntax), but it's overall been fine.
EDIT:
I should mention that I'm simply following the instructor's instructions and writing the same code as him.
Right now, however, I'm simply stuck. I've got this routing in scrumboard.config.js:
(function () {
"use strict";
angular.module('scrumboard.demo', ["ngRoute"])
.config(["$routeProvider", config])
.run(["$http", run]);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "/static/html/scrumboard.html",
controller: "ScrumboardController",
})
.when('/login', {
templateUrl: "/static/html/login.html",
controller: "LoginController",
})
.otherwise('/');
}
function run($http) {
$http.defaults.xsrfHeaderName = 'X-CSRFToken';
$http.defaults.xsrfCookieName = 'csrftoken';
}
})();
And this controller for login.html:
(function() {
"use strict";
angular.module("scrumboard.demo", [])
.controller("LoginController",
["$scope", "$http", "$location", LoginController]);
function LoginController($scope, $http, $location) {
$scope.login = function () {
$http.post('/auth_api/login/', $scope.user)
.then(function (response){
$location.url("/");
},
function(error) {
//failure
$scope.login_error = "Invalid username or password";
});
};
};
})();
When navigating to localhost:8000/#!/login I can see my form:
<form ng-submit="login()">
<div style="...">{{ login_error }}</div>
<div>
<label>Username</label>
<input type="text" ng-model="user.username"/>
</div>
<div>
<label>Password</label>
<input type="password" ng-model="user.password"/>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
But for some strange reason my console keeps telling me that my LoginController isn't registered.
Could anyone please help me in the right direction?
Sorry if I'm missing any sort of files, but I'm very new to Angular, so I don't really know what to add.
If you need any additional information, please tell me!
remove [] from your controller's defination for login.html.
angular.module("scrumboard.demo")
.controller("LoginController",
["$scope", "$http", "$location", LoginController]);
You are declaring the module scrumboard.demo twice.
Remove the [] in
angular.module("scrumboard.demo")
.controller("LoginController",
["$scope", "$http", "$location", LoginController]);
Without the second argument of angular.module() it is a getter, otherwise it is a setter
In the entry point html, the script tag for file scrumboard.config.js should precede the file controller file. Also as #charlietfl said declaring twice should be removed.
Like this,
<script src="your_path/scrumboard.config.js"></script>
<script src="your_path/scrumboard.controller.js"></script>
Hope this would rectify the problem.
My setup is NodeJS, MongoDB, and Angular. I'm currently trying to add POSTing capability to my test code but can't quite wrap my head around it. Currently I can pull data from the DB and I threw together a quick and dirty form/factory based on a number of examples I've seen to try to get the POST function working.
The problem I'm running into is actually getting the values to be added to the DB. When I submit the form, a new ObjectID is created in the DB with a "_v" field and a value of 0. So I know the POST is at least being sent to the DB, but the values I want are not. I'm sure I'm doing something stupid and any help is greatly appreciated.
Here is my controller/factory setup: (I named the POST factory "taco" so it would stand out. Also because they're delicious.)
angular.module('app', ['ngRoute'])
.factory('Users', ['$http', function($http) {
return $http.get('/users');
}])
.factory('taco', ['$http', function($http) {
return $http.post('/users');
}])
.controller('UserController', ['$scope', 'Users', function($scope, Users) {
Users.success(function(data) {
$scope.users = data;
}).error(function(data, error) {
console.log(error);
$scope.users = [];
});
}])
.controller('ExampleController', ['$scope', 'taco', function($scope, taco) {
$scope.submit = function() {
if ($scope.users.name) {
$scope.name.post(this.name);
$scope.name = '';
}
};
}]);
Here is my form:
<div>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter the things:<br/>
<input type="text" ng-model="name" name="user.name" placeholder="name" /><br/>
<input type="text" ng-model="emp_id" name="user.emp_id" placeholder="EID" /><br/>
<input type="text" ng-model="loc" name="user.loc" placeholder="location" /><br/>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
To post using the $http service you can do:
angular.module('myApp')
.controller('MyController', function($scope, $http) {
$http.post('/destination', {my: 'data'});
});
You're not sending any data in your POST request. The taco service just executes a $http.post call and returns the promise.
Please look at the $http service documents: https://docs.angularjs.org/api/ng/service/$http
I would define a function submit that would send the data once a user clicks on submit:
$scope.submit = function() {
$http.post('/destination', {my: 'data'});
}
I am trying to create a seed application using Angular JS,RequireJS & Framework 7. I have so far created the following folder structure.
My main folder looks like below:
and my scripts folder looks like this :
and my libraries are :
I was able to the view -> controller flow working properly. But when I try to inject a service object to the controller I get the following error.
I am sure I must be missing something. I have given my code below:
require-main:
(function() {
require.config({
baseUrl: "scripts",
// alias libraries paths
paths: {
'angular': '../libs/angular',
'angular-route': '../libs/angular-route',
'angular-animate':'../libs/angular-animate',
'angularAMD': '../libs/angularAMD.min',
'Framework7':'../libs/framework7',
'UserController':'controller/UserCtrl',
'WebCallManager':'services/WebCallManager'
},
// Add angular modules that does not support AMD out of the box, put it in a shim
shim: {
'angularAMD': ['angular'],
'angular-route': ['angular'],
'angular-animate':['angular'],
'Framework7':{exports: 'Framework7'}
},
//kick start application
deps: ['app']
});
require(['Framework7'], function(Framework7) {
f7 = new Framework7({
modalTitle: 'Seed App',
swipePanel: 'left',
animateNavBackIcon: true
});
return {
f7: f7
};
});
})();
app.js :
define(['angularAMD', 'angular-route','angular-animate'], function (angularAMD) {
var app = angular.module("app", ['ngRoute','ngAnimate']);
app.config(function ($routeProvider) {
$routeProvider.when("/", angularAMD.route({ templateUrl: '../pages/login.html',controller: 'UserController'}));
$routeProvider.when("/login", angularAMD.route({ templateUrl: '../pages/home.html', controller: 'UserController'}));
});
angularAMD.bootstrap(app);
return app;
});
UserController :
define(['app'], function (app) {
app.register.controller('UserController', function ($scope,$location,webcallService) {
$scope.loginUser = function(){
console.log("Login User Called...");
$location.path('/login').replace();
console.log("View Navigated...");
};
$scope.slidePanel = function(){
f7.openPanel('left');
};
$scope.doWebCall = function(){
console.log("Doing the Web Call...");
webcallService.sendGetRequest();
};
});
});
WebCallManager.js (Service)
define(['app'], function (app) {
app.service('webcallService', function() {
var self = this;
self.sendGetRequest = function() {
console.log("Sending HTTP Get Request");
}
self.sendPostRequest = function() {
console.log("Sending HTTP Post Request");
}
});
});
And my pages :
index.html:
<!DOCTYPE html>
<html>
<head>
<script data-main="scripts/main" src="libs/require.js"></script>
</head>
<body>
<div>
<div class="slide-animation page-content" ng-view ></div>
</div>
</body>
</html>
login.html:
<div class="content-block login-input-content">
<div class="store-data list-block">
<div>
<input type="text" class="login-name" placeholder="Username">
</div>
<div>
<input type="password" class="password" placeholder="Password">
</div>
<a class="multi-language" href="#"><i class="icon ios7-world-outline"></i><span>english</span></a>
</div>
</div>
<div class="content-block login-btn-content">
<button ng-click="loginUser()" class="button button-big button-submit login-submit">Login</button>
</div>
Home.html:
<div>
<h3>Welcome to Mobility In Angular-JS</h3>
<div class="content-block login-btn-content">
<button ng-click="doWebCall()" class="button button-big button-submit login-submit">Send Get</button>
<br/><br/>
<button ng-click="doWebCall()" class="button button-big button-submit login-submit">Send Post</button>
</div>
Could Anyone help me out ??. YOu can also download and run the entire project here.
You are registering the service as webcallService:
app.service('webcallService', function() {
But inject the $webcallService in the controller:
app.register.controller('UserController', function ($scope, $location, $webcallService) {
Choose one, the one without $ is recommend though, so declare your controller with webcallService:
app.register.controller('UserController', function ($scope, $location, webcallService) {
EDIT: Found one more problem, after reading the angularAMD documentation, it seems you have to add the requirejs module WebCallManager that contain the webcallService angularjs service as a dependency in define() as well.
Therefore, it should be like this:
define(['app', 'WebCallManager'], function (app) {
app.register.controller('UserController', function ($scope,$location,webcallService) {
Otherwise, the module WebCallManager will not be loaded on-demand.
EDIT: Found the third problem, you register the controller via app.register, but register the service directly via app.. You need to be consistent here, but the app.register has been deprecated (See this thread).
Therefore the best would be removing the app.register like this:
app.controller('UserController', ..
And in app.js change from:
angularAMD.bootstrap(app);
return app;
to
return angularAMD.bootstrap(app);
Hope this helps.
From this stackoverflow question, my understanding is that I should be using services to pass data between controllers.
However, as seen in my example JSFiddle, I am having trouble listening to changes to my service when it is modified across controllers.
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('App.data.status', function() {
$scope.status = App.data.status;
});
})
.controller('Ctrl2', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('status', function() {
App.data.status = $scope.status;
});
})
.service('App', function () {
this.data = {};
this.data.status = 'Good';
});
In my example, I am trying to subscribe to App.data.status in Ctrl1, and I am trying to publish data from Ctrl1 to App. However, if you try to change the input box in the div associated with Ctrl2, the text does not change across the controller boundary across to Ctrl1.
http://jsfiddle.net/VP4d5/2/
Here's an updated fiddle. Basically if you're going to share the same data object between two controllers from a service you just need to use an object of some sort aside from a string or javascript primitive. In this case I'm just using a regular Object {} to share the data between the two controllers.
The JS
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.localData1 = App.data;
})
.controller('Ctrl2', function ($scope, App) {
$scope.localData2 = App.data;
})
.service('App', function () {
this.data = {status:'Good'};
});
The HTML
<div ng-controller="Ctrl1">
<div> Ctrl1 Status is: {{status}}
</div>
<div>
<input type="text" ng-model="localData1.status" />
</div>
<div ng-controller="Ctrl2">Ctrl2 Status is: {{status}}
<div>
<input type="text" ng-model="localData2.status" />
</div>
</div>
Nothing wrong with using a service here but if the only purpose is to have a shared object across the app then I think using .value makes a bit more sense. If this service will have functions for interacting with endpoints and the data be sure to use angular.copy to update the object properties instead of using = which will replace the service's local reference but won't be reflected in the controllers.
http://jsfiddle.net/VP4d5/3/
The modified JS using .value
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, sharedObject) {
$scope.localData1 = sharedObject;
})
.controller('Ctrl2', function ($scope, sharedObject) {
$scope.localData2 = sharedObject;
})
.value("sharedObject", {status:'Awesome'});
I agree with #shaunhusain, but I think that you would be better off using a factory instead of a service:
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.localData1 = App.data;
})
.controller('Ctrl2', function ($scope, App) {
$scope.localData2 = App.data;
})
.factory('App', function () {
var sharedObj = {
data : {
status: 'Good'
}
};
return sharedObj;
});
Here are some information that might help you understand the differences between a factory and a service: When creating service method what's the difference between module.service and module.factory
This is my template:
<div class="span12">
<ng:view></ng:view>
</div>
and this is my view template:
<h1>{{stuff.title}}</h1>
{{stuff.content}}
I am getting the content as html and I want to display that in a view, but all I am getting is raw html code. How can I render that HTML?
Use-
<span ng-bind-html="myContent"></span>
You need to tell angular to not escape it.
To do this, I use a custom filter.
In my app:
myApp.filter('rawHtml', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}]);
Then, in the view:
<h1>{{ stuff.title}}</h1>
<div ng-bind-html="stuff.content | rawHtml"></div>
In angular 4+ we can use innerHTML property instead of ng-bind-html.
In my case, it's working and I am using angular 5.
<div class="chart-body" [innerHTML]="htmlContent"></div>
In.ts file
let htmlContent = 'This is the `<b>Bold</b>` text.';
You shoud follow the Angular docs and use $sce - $sce is a service that provides Strict Contextual Escaping services to AngularJS. Here is a docs: http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe
Let's take an example with asynchroniously loading Eventbrite login button
In your controller:
someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin',
function($scope, $sce, eventbriteLogin) {
eventbriteLogin.fetchButton(function(data){
$scope.buttonLogin = $sce.trustAsHtml(data);
});
}]);
In your view just add:
<span ng-bind-html="buttonLogin"></span>
In your services:
someAppServices.factory('eventbriteLogin', function($resource){
return {
fetchButton: function(callback){
Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){
callback(widget_html);
})
}
}
});
So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:
<html>
<body ng-app="yourApp">
<div class="span12">
<div ng-view=""></div>
</div>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
Then yourView.html could just be:
<div>
<h1>{{ stuff.h1 }}</h1>
<p>{{ stuff.content }}</p>
</div>
scripts.js could have your controller with data $scope'd to it.
angular.module('yourApp')
.controller('YourCtrl', function ($scope) {
$scope.stuff = {
'h1':'Title',
'content':"A paragraph..."
};
});
Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)
angular.module('yourApp', [])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/yourView.html',
controller: 'YourCtrl'
});
});
I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data