First off all, I want to show the json data from my codeigniter controller in view page through $http post method.
The problem is that I'm facing some problems, then I can't make it works.
Code:
.state('GetData', {
url: "/getdata",
templateUrl: base_url + "loadl/getdata",
data: {
pageTitle: 'Datapage'
},
controller: "Mycontroller",
resolve: {
deps: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'Myapp',
files: [
base_url + 'application/assets/js/controllers/Mycontroller.js'
]
});
}]
}
})
Controller:
angular.module('Myapp')
.controller('Mycontroller', function($rootScope, $scope, $http, $timeout) {
$http.get(base_url + "getData/show").
success(function(response) {
$scope.data1 = response.data;
});
});
CI controller
public function show() {
echo '{"data":[{"sl_num":"1","name":"James","category":"1"}]}';
}
View:
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" placeholder="John" class="form-control" ng-model="data1.name" />
</div>
Upadate with the my answer i will work
angular.module('Myapp')
.controller('Mycontroller', function($rootScope, $scope, $http, $timeout) {
$http.get(base_url + "getData/show").
success(function(response) {
console.log(response);
$scope.data1 = response.data[0].name;
console.log($scope.data1);
});
});
View:
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" placeholder="John" class="form-control" ng-model="data1" />
</div>
Related
Hi I'm trying to create a component, it works fine in controller, however not binding values to view.
My Component is as below
app.component("bdObjects", {
templateUrl: "app/templates/components/BusinessObjects.html",
controller: ["$scope", "$http", "$log", "API_ROOT", "VisDataSet",
function ($scope, $http, $log, API_ROOT, VisDataSet) {
$scope.fnAdd = function() {
$scope.objectId = "";
$scope.objectName = "Test Object";
console.log($scope.objectName);
}
$scope.cancelAdd = function() {
if($scope.items.length > 0) {
$log.info($scope.items[0]);
$scope.fnPopulateForm($scope.items[0]);
}
}
}],
bindings: {
data: "=",
objectId: "=",
objectName: "="
}
});
My Template
<div class="general-form">
<input type="hidden" name="id" ng-model="objectId">
<label>Name:</label>
<br>
<input class="form-control" name="name" placeholder="Name" ng-model="objectName">
<br>
</div>
So on add button I tried to assign value to input box. but it's not taking. and I want to make that two way binding. so later I'll have save button, so changing the value in TextBox will replace in Controller.
Thanks.
In controller, change $scope by this or some alias, e.g.
controller: ["$scope", "$http", "$log", "API_ROOT", "VisDataSet",
function ($scope, $http, $log, API_ROOT, VisDataSet) {
var ctrl = this;
ctrl.fnAdd = function() {
ctrl.objectId = "";
ctrl.objectName = "Test Object";
console.log(ctrl.objectName);
}
// Not sure about items: you haven't defined it,
// neither fnPopulateForm...
ctrl.cancelAdd = function() {
if(ctrl.items.length > 0) {
$log.info($scope.items[0]);
ctrl.fnPopulateForm(ctrl.items[0]);
}
}
}],
And in view, use the default controller binding i.e $ctrl
<div class="general-form">
<input type="hidden" name="id" ng-model="$ctrl.objectId">
<label>Name:</label>
<br>
<input class="form-control" name="name" placeholder="Name" ng-model="$ctrl.objectName">
<br>
</div>
You can also change $ctrl into whatever you want in a controllerAs declaration of the component, i.e.
app.component("bdObjects", {
templateUrl: "app/templates/components/BusinessObjects.html",
controller: ["$scope", "$http", "$log", "API_ROOT", "VisDataSet",
function ($scope, $http, $log, API_ROOT, VisDataSet) {
//...
}],
controllerAs: 'bd',
bindings: {
//...
}
});
and in the view:
I tried with $timeout() and it got working.
Hey check this JS fiddle
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<input type="hidden" name="id" ng-model="objectId">
<label>Name:</label>
<br>
<input class="form-control" name="name" placeholder="Name" ng-model="objectName">
<br>
<button ng-click="fnAdd()">
button
</button>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.fnAdd = function() {
$scope.objectId = "";
$scope.objectName = "Test Object";
console.log($scope.objectName);
}
$scope.cancelAdd = function() {
if ($scope.items.length > 0) {
$log.info($scope.items[0]);
$scope.fnPopulateForm($scope.items[0]);
}
}
});
</script>
I tried creating a service in angularjs but I keep getting angular.js:10467 Error: [ng:areq] Argument 'MainController' is not a function, got undefined.
html:
<div ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find"/>
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="services/Screamer.js"></script>
my app.js:
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker', []).controller('MainController', function(screamer, $log, $http, $scope, $interval){
$http({
method : 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response){
console.log(response);
$scope.data = response.data;
}, function(response){
console.log(response);
});
my service in service.js
(function() {
'use strict';
angular.module('NoteTaker', []).factory('screamer', function(){
return {
say: "blahbalh"
};
});
}());
angular.module(name, dependencies) creates a new module. If you want to add to an existing one, use angular.module(name):
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker')
.controller('MainController', function(screamer, $log, $http, $scope, $interval) {
$http({
method: 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response) {
console.log(response);
$scope.data = response.data;
}, function(response) {
console.log(response);
});
});
// service.js
(function() {
'use strict';
angular.module('NoteTaker').factory('screamer', function() {
return {
say: "blahbalh"
};
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="NoteTaker" ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
I create a new module on line 1, and add the controller & service to it.
tcooc answered your question, but I'll try to make it a little easier to understand:
app.module('myModule', ['dep1', 'dep2']); // passing an array creates a NEW module
Access the newly created module by calling the same method, but without the array of dependencies:
app.module('myModule')
.controller('MyController')
.service('MyService')
.factory('MyFactory');
Or, just attach everything to the first module call:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', function(...) {})
.service('MyService', function(...) {})
.factory('MyFactory', function(...) {});
Also, it helps to write dependency injection like this:
MyController.$inject = ['$scope', '$location', '$log'];
function MyController($scope, $location, $log) {
}
MyService.$inject = ['$http'];
function MyService($http) {
}
This makes it clear what is getting injected where. And it makes your code much more readable, since you can now write this:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', MyController)
.service('MyService', MyService);
The below code describe my app.js file.
(function () {
'use strict';
angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/users/login', {
controller: 'LoginController',
templateUrl: 'login/login.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'register/register.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/users/login' });
}
})();
The one below describe my login controller.js file: I wrote this route for logging in registered users to the database and creating tokens once the username and password are correct. What I want now is to create an auto route that will redirect the users to the home page once the password and username is correct.
(function () {
'use strict';
angular
.module('app')
.service('Users1', function($http) {
this.logUser = function(user) {
return $http.post("/users/login", user).
then(function(response) {
return response;
}, function(response) {
alert("Error logging in user.");
});
}
})
// .controller('RegisterController', RegisterController);
.controller("LoginController", function($scope, $location, Users1) {
$scope.back = function() {
$location.path("/users/login");
}
$scope.login = function(user) {
Users1.logUser(user).then(function(doc) {
var userUrl = "/" + doc.data.id;
$location.path(userUrl);
}, function(response) {
alert(response);
});
}
})
})();
Below is the html file for the login controller file:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" role="form">
<div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" ng-model="user.username" required />
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="user.password" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary" ng-click="login(user)">Login</button>
Register
</div>
</form>
$scope.login = function(user) {
Users1.logUser(user).then(function(
$location.path("/");
}, function(response) {
alert(response);
});
}
If you just want to redirect user to the home page. and if you want the userid as urlParams then you should go with this
.when('/:id', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
and the controller
$scope.login = function(user) {
Users1.logUser(user).then(function(doc) {
var userUrl = "/" + doc.data.id;
$location.path(userUrl);
}, function(response) {
alert(response);
});
}
you can use run method to redirect user to home on landing.
You can check when even ever there is route change and redirect him to right place.
$scope.$on('$routeChangeStart', function (event, next, current) {
//add your logic here. if user next contains next route.
});
I have this md-dialog which has an input. I'm passing the model of the input when I click the top up button but on my controller, it is undefined.
<md-dialog aria-label="Top Up User" ng-cloak>
<md-dialog-content>
<div class="md-dialog-content">
<form>
<md-input-container class="md-block">
<label>Amount</label>
<input required type="number" name="amount" ng-model="topup.amount" min="1"
ng-pattern="/^1234$/" />
</md-input-container>
<md-dialog-actions layout="row" ng-show="!vm.loading">
<md-button ng-click="vm.closeDialog()">
Cancel
</md-button>
<md-button ng-click="vm.topUp(topup.amount)" style="margin-right:20px;">
Top Up
</md-button>
</md-dialog-actions>
<div layout="row" layout-align="space-around">
<md-progress-circular md-mode="indeterminate" ng-show="vm.loading"></md-progress-circular>
</div>
</form>
</div>
</md-dialog-content>
</md-dialog>
Controller:
(function(){
angular
.module('app')
.controller('MainController', [
'navService', '$mdSidenav', '$mdDialog', '$log', '$q', '$state', '$mdToast', 'Pubnub', 'mongolabService', '$scope',
MainController
]);
function MainController(navService, $mdSidenav, $mdDialog, $log, $q, $state, $mdToast, Pubnub, mongolabService, $scope) {
var vm = this;
function showActions($event) {
var self = this;
$mdDialog.show({
controller: [ '$mdDialog', TopUpController],
controllerAs: 'vm',
templateUrl: 'app/views/partials/topup.html',
targetEvent: $event,
bindToController : true,
clickOutsideToClose:true
});
function TopUpController () {
var vm = this;
vm.topUp = topUp;
vm.loading = false;
vm.closeDialog = closeDialog;
function closeDialog() {
$mdDialog.hide();
}
function querySearch (query) {
return query ? $scope.users.filter( createFilterFor(query) ) : $scope.users;
}
function topUp(amount) {
var topUpCallback = {
error: function(response){
vm.loading = false;
showSimpleToast("Error occurred");
console.log(response);
}, success: function(response){
showSimpleToast("Top up success");
}
}
//Amount is undefined
showSimpleToast("amount: " + amount);
}
}
}
function showSimpleToast(title) {
$mdToast.show(
$mdToast.simple()
.content(title)
.hideDelay(2000)
.position('bottom right')
);
}
}
})();
Its strange. change
showSimpleToast("amount: " + amount);
to
showSimpleToast("amount: " + vm.amount);
and let see what happens
Can you change the way you're using topup property like this (just for 1 style coding vm/$scope):
In input
<input required type="number" name="amount" ng-model="vm.topup.amount" min="1" ...
In button:
<md-button ng-click="vm.topUp(topup.amount)" style="margin-right:20px;">
And init topup object in your controller:
vm.topup = {amount: ''};
I think the problem is you didn't init your topup object before use its amount property
I noticed that the amount is just getting undefined when I type on the input. I added allowInvalid to the <input> and it worked.
ng-model-options="{allowInvalid: true}"
The SignupCtrl controller is not binding to signup view. Even when i press the submit button it don't work. But when i place ng-controller=SignupCtrl in the form tag it works. Just wondering why ui-router state parameter controller was not working.
index.html
<html class="no-js" ng-app="mainApp" ng-controller="MainCtrl">
<head> ....
</head>
<body class="home-page">
<div ui-view="header"></div>
<div ui-view="content"></div>
<div ui-view="footer"></div>
...
signup.html
<div class="form-container col-md-5 col-sm-12 col-xs-12">
<form class="signup-form">
<div class="form-group email">
<label class="sr-only" for="signup-email">Your email</label>
<input id="signup-email" type="email" ng-model="user.email" class="form-control login-email" placeholder="Your email">
</div>
<!--//form-group-->
<div class="form-group password">
<label class="sr-only" for="signup-password">Your password</label>
<input id="signup-password" type="password" ng-model="user.password" class="form-control login-password" placeholder="Password">
</div>
<!--//form-group-->
<button type="submit" ng-click="createUser()" class="btn btn-block btn-cta-primary">Sign up</button>
<p class="note">By signing up, you agree to our terms of services and privacy policy.</p>
<p class="lead">Already have an account? <a class="login-link" id="login-link" ui-sref="login">Log in</a>
</p>
</form>
</div><!--//form-container-->
app.js
angular
.module('mainApp', [
'services.config',
'mainApp.signup'
])
.config(['$urlRouterProvider', function($urlRouterProvider){
$urlRouterProvider.otherwise('/');
}])
signup.js
'use strict';
/**
* #ngdoc function
* #name mainApp.signup
* #description
* # SignupCtrl
*/
angular
.module('mainApp.signup', [
'ui.router',
'angular-storage'
])
.config(['$stateProvider', function($stateProvider){
$stateProvider.state('signup',{
url: '/signup',
controller: 'SignupCtrl',
views: {
'header': {
templateUrl: '/pages/templates/nav.html'
},
'content' : {
templateUrl: '/pages/signup/signup.html'
},
'footer' : {
templateUrl: '/pages/templates/footer.html'
}
}
});
}])
.controller( 'SignupCtrl', function SignupController( $scope, $http, store, $state) {
$scope.user = {};
$scope.createUser = function() {
$http({
url: 'http://localhost:3001/users',
method: 'POST',
data: $scope.user
}).then(function(response) {
store.set('jwt', response.data.id_token);
$state.go('home');
}, function(error) {
alert(error.data);
});
}
});
There is a working plunker. Firstly, check this Q & A:
Are there different ways of declaring the controller associated with an Angular UI Router state
Where we can see, that
controller does not belong to state. It belongs to view!
This should be the state definition:
$stateProvider.state('signup',{
url: '/signup',
//controller: 'SignupCtrl',
views: {
'header': {
templateUrl: 'pages/templates/nav.html'
},
'content' : {
templateUrl: 'pages/signup/signup.html',
controller: 'SignupCtrl',
},
'footer' : {
templateUrl: 'pages/templates/footer.html'
}
}
});
Check it here
You need a template to bind a controller.
In the docs ui-router Controllers
Controllers
You can assign a controller to your template. Warning: The controller
will not be instantiated if template is not defined.