I have a variable in my controller and would like to assign a value later, when click on a button. i.e.
var app = angular.module('myApp', ['ngRoute']);
....
var userArray = [
{name: "John", age: 25}, {name: "Jim", age: 30}
];
app.controller('Page2Controller', function($scope) {
$scope.message = 'Look! I am from page 2.';
$scope.newArray = [];
$scope.addUsers = function(){
scope.newArray = userArray;
console.log($scope.newArray);
}
}
app.config(function($routeProvider) {
$routeProvider
.when('/page2', {
templateUrl : 'pages/page2.html',
controller : 'Page2Controller'
...
page2.html
<div>
<p>{{ message }}</p>
<ul>
<li ng-repeat="user in Page2Controller.newArray">{{user.name}}</li>
</ul>
</div>
index.html
<body ng-controller="MainController">
<div id="sideMenu">
<h2>Campaign</h2>
<ul>
<li>Home</li>
<li>Page 2</li>
<li>Page 3</li>
<li>Page 4</li>
</ul>
</div>
<div ng-view></div>
</body>
I don't understand why the $scope.user is displayed in console but in html page the "ng-repeat" doesn't display the users. May it be that ng-repeat cannot display data that was added dynamically?
Can someone help me? Appreciate that.
You never called that function I guess..
var app = angular.module('myApp', []);
var userArray = [{name: "John", age: 25}, {name: "Jim", age: 30}];
app.controller('Page2Controller', function($scope) {
$scope.message = 'Look! I am from page 2.';
// $scope.newArray = [];
$scope.addUsers = function(){
$scope.newArray = userArray;
console.log($scope.newArray);
}
$scope.addUsers();
});
and html
<div ng-controller="Page2Controller">
<p>{{ message }}</p>
<ul>
<li ng-repeat="user in newArray">{{user.name}}</li>
</ul>
</div>
I have statically used your controller as i didn't implement the ngRoute.
Try switching to:
<li ng-repeat="user in scope.newArray">{{user.name}}</li>
I don't think 'Page2Controller' is known in the template context.
First of all you have need a ng-click derective where you have to click such as
<button type="button" ng-click="asigningValue()"></button>
Then in your Controller you have to assign what you want such as in controller
After that you have need to bind you assign value in the directive such as
app.controller('Page2Controller', function($scope) {
$scope.asigningValue=function(){
$scope.message = 'Look! I am from page 2.';
}
}
Then show using directive using data binding as
<p ng-bind-html="message"></p>
Hope it will be helpful!
Thank you!
Related
I trying to create a unordered list using controller and view page. Please find the controller below:
(function() {
'use strict';
angular
.module('app.sdb')
.controller('SdbController', SdbController)
SdbController.$inject = ['logger'];
/* #ngInject */
function SdbController(logger) {
var vm = this;
vm.models = {
selected: null,
lists: {"A": [], "B": []}
};
for(var i=1;i<=3;i++) {
vm.models.lists.A.push({label: "Item A" + i});
vm.models.lists.B.push({label: "Item B" + i});
}
activate();
function activate() {
vm.title = 'Safe Digital Board';
logger.info('Activation', 'Sdb Controller', 'Template Rendered');
}
}
})();
Please find the mark up below:
<div>
<ul>
<li ng-repeat="item in vm.models"> Hello {{item.label}} </li>
</ul>
</div>
But am getting only the below O/P:
Hello
Hello
Seeking help... Please advise
Problem is with your model object. Your ng-repeat should be ng-repeat="item in vm.models.lists.A"
Please find a working plunker
<div>
<ul>
<li ng-repeat="item in vm.models.lists.A"> Hello {{item.label}} </li>
</ul>
</div>
To show both lists you need to write your template as shown below:
<div>
<ul ng-repeat="items in vm.models.lists">
<li ng-repeat="item in items"> Hello {{item.label}} </li>
</ul>
</div>
try using $scope and create an array for $scope.vm.models, like:
.controller('SdbController', ['$scope', $log,
function($scope, $log) {
$scope.reset = function() {
$scope.vm = {};
$scope.vm.models = [{label:"element01"},
};
$scope.reset();
}
}]);
I'm trying to make an editable list of items. There is an editing mode of each item.
HTML:
<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items">
<div class="edit-off" ng-hide="editMode">...</div>
<div class="edit-on" ng-show="editMode">...</div>
<button ng-click="toggleEdit()">Edit</button>
</li>
</ul>
JavaScript:
angular.module("app", [])
.controller("ItemCtrl", function($scope) {
$scope.items = [...]; // list of items
$scope.editMode = false;
$scope.toggleEdit = function() {
$scope.editMode = !$scope.editMode;
};
});
I know that this code isn't correct since I attached editMode to the controller scope, not to ngRepeat scope. With this code, whenever I click at any button, all items will turn into editing mode.
All I want is that every item has its own editMode property in its scope, so that I can edit them individually.
put your property on each item:
<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items">
<div class="edit-off" ng-hide="item.editMode">...</div>
<div class="edit-on" ng-show="item.editMode">...</div>
<button ng-click="toggleEdit(item)">Edit</button>
</li>
</ul>
angular.module("app", [])
.controller("ItemCtrl", function($scope) {
$scope.items = [...]; // list of items
$scope.toggleEdit = function(item) {
item.editMode = !item.editMode;
};
});
You can use $index like this:
angular.module("app", [])
.controller("ItemCtrl", function($scope) {
$scope.items = [...]; // list of items
$scope.editMode = [];
$scope.toggleEdit = function(index) {
$scope.editMode[index] = !$scope.editMode[index];
};
});
HTML:
<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items">
<div class="edit-off" ng-hide="editMode[$index]">...</div>
<div class="edit-on" ng-show="editMode[$index]">...</div>
<button ng-click="toggleEdit($index)">Edit</button>
</li>
</ul>
Demo: https://jsfiddle.net/iRbouh/rftfx7j4/
You can add the property in each item and use it to edit.
$scope.items = [{name: 'misko', gender: 'male'},{name: 'misko1', gender: 'male'}];
angular.forEach($scope.items, function(obj) {
obj["editMode"] = false
});
in view
<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items">
<div class="edit-off" ng-hide="editMode[$index]">...</div>
<div class="edit-on" ng-show="editMode[$index]">...</div>
<button ng-click="item.editMode = !item.editMode">Edit</button>
</li>
</ul>
Use $index.
HTML:
<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items track by $index">
<div class="edit-off" ng-hide="editMode">...</div>
<div class="edit-on" ng-show="editMode">...</div>
<button ng-click="toggleEdit($index)">Edit</button>
</li>
</ul>
JS:
angular.module("app", [])
.controller("ItemCtrl", function($scope) {
$scope.items = [...]; // list of items
$scope.toggleEdit = function($index) {
setEditMode($scope.items[$index]);
};
});
function setEditMode(item) {
item.editMode = false;
}
Add the editMode attribute to each item, as said in #John's answer.
Here's the working Plunker:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id:2, ds: 'test1' },
{ id:2, ds: 'test2' },
{ id:2, ds: 'test3'}]; // list of items
$scope.toggleEdit = function($index) {
$scope.items[$index].editMode = !$scope.items[$index].editMode;
};
});
There are a lots way can implement this, see example:
<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items">
<div class="edit-off" ng-hide="editMode[$index]">{{editMode[$index]}}</div>
<div class="edit-on" ng-show="editMode[$index]">{{editMode[$index]}}</div>
<button ng-click="toggleEdit($index)">Edit</button>
</li>
var myApp = angular.module("myApp", [])
.controller("ItemCtrl", function($scope) {
$scope.items = ["aaa","bbb","ccc"]; // list of items
$scope.editMode = [true,true,true];
$scope.toggleEdit = function(index) {
$scope.editMode[index] = !$scope.editMode[index];
};
});
http://jsfiddle.net/Lvc0u55v/7052/
I'm facing some problems with my simple code (study), i really need some help to fix this.
First of all i have a php file who provides a json.
app.php
<?php
$dbh = new PDO('mysql:host=localhost;dbname=caio', 'root', '');
$a = $dbh->query("SELECT * FROM usuario");
$b = json_encode($a->fetchAll(PDO::FETCH_ASSOC));
echo $b;
?>
It's a simple json with id, name and surname
Also i have a Js file to get this.
app.js
var meuApp = angular.module('meuApp', ['ui.router']);
meuApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('usuarios.detail', {
url: "/usuarios/{id}",
templateUrl: 'uDetail.html'
});
});
meuApp.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('app.php')
.success(function(data) {
$scope.usuarios = data;
console.log(data);
//just checking in the console...
var id = data[0].id
console.log(id);
var nome = data[0].nome
console.log(nome);
});
}]);
and finally my html file
<html ng-app="meuApp" lang="pt">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="userCtrl">
<ul>
<li ng-repeat="usuario in usuarios">
<a ui-sref="usuarios.detail">{{usuario.nome}}</a>
</li>
</ul>
</div>
</body>
If i want to show, ok the code is working, but i want to click in each name and then the template shows me the id, name and surname of this "person". That's my problem.
Thank you guys.
Here you need to pass person object from one state to another state.
For that you can use params attribute of ui-router. When you click any perticular person at that time you need to pass id also while routing from one state to another because you already configure in url "/usuarios/{id}".
ui-router will match that property from params and will set in url.
Now you can successfully pass clicked object from one state to another. Get that object with $stateParams service of ui-router in controller of usuarios.detail state so that you can display in uDetail.html
meuApp.config(function($stateProvider, $urlRouterProvider,$stateParams){
$stateProvider
.state('usuarios.detail', {
url: "/usuarios/{id}",
params: {
id: null,
person:null
},
templateUrl: 'uDetail.html',
controller: function($scope, $stateParams) {
$scope.portfolioId = $stateParams.id;
$scope.person = $stateParams.person;
console.log("State parameters " + JSON.stringify($stateParams));
}
});
});
and in your template where you are showing the list.
<ul>
<li ng-repeat="usuario in usuarios">
<a ui-sref="usuarios.detail({ id:usuario.id,person:usuario})">{{usuario.nome}}</a>
</li>
</ul>
See above code which I gave for your reference.
You can see this Demo for in detail idea of ui-router.
You need some minor changes in order to get your code working, check the files bellow:
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="userCtrl">
<ul>
<li ng-repeat="user in users">
<a ui-sref="users.detail({id: user.id, user: user})">{{user.name}}</a>
</li>
</ul>
</div>
<div ui-view></div>
</body>
app.js
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider) {
$stateProvider
.state('users', {
abstract: true,
url: 'users',
template: '<div ui-view></div>'
})
.state('users.detail', {
url: '/:id',
templateUrl: 'users.detail.html',
params: {
user: null
},
controller: function($scope, $stateParams) {
$scope.user = $stateParams.user;
}
});
});
app.controller('userCtrl', ['$scope', '$http',
function($scope, $http) {
// replace this with your service call
$scope.users = [{
id: 1,
name: 'john',
surname: 'doe'
}, {
id: 2,
name: 'mary',
surname: 'poppins'
}];
}
]);
user.detail.html
<fieldset>
<div>
<label>id: </label> {{user.id}}
</div>
<div>
<label>name: </label> {{user.name}}
</div>
<div>
<label>surname: </label> {{user.surname}}
</div>
</fieldset>
I've similarly asked this before, but neither solution proved useful.
I currently have a store app built with AngularJS, my problem is, I need to be able to click on one item and open into the "item" view and display only the information with a matching ID from the items array stored in a services.
For example. Item one displayed on store view has an id of 1, and on the store displays the product name etc. When clicked, the item is opened with the item view to display just that product and it's information.
Here's my store Controller:
'use strict';
angular.module('angularStoreApp')
.controller('storeCtrl', function($scope, StoreService){
$scope.items = StoreService.items();
});
Services (Shortened to save spare, there's 12 other items).
'use strict';
angular.module('angularStoreApp')
.service("StoreService", function() {
var items = [ {
itemId: 1,
qty: 0,
stock: 5,
price: 99.00,
name: 'Almond Toe Court Shoes, Patent Black',
category: 'Womens Footerwear'
},
{
qty: 0,
stock: 4,
price: 42.00,
name: 'Suede Shoes, Blue',
category: 'Womens Footerwear'
}];
this.items = function() {
return items;
};
});
Store View
<!-- Start of item iteration -->
<div ng-repeat="item in items">
<!-- Start of item -->
<div class="item">
<div class="item_info">
<img src="http://i.imgur.com/Bn1iB6X.jpg"/>
<div class="item_footer">
<div class="info_text">
<h2>{{item.name| limitTo: 8}}...</h2>
<span>{{item.price | currency}}</span>
</div>
<div class="icon">
<a ng-href="#"><button role="button">More</button></a>
</div>
</div>
</div>
</div>
<!-- End of item -->
</div>
<!-- End of item iteration-->
Item Ctrl
'use strict';
angular.module('angularStoreApp')
.controller('itemCtrl', function ($scope, StoreService) {
$scope.items = StoreService.items();
});
Item View
<div ng-include="'components/navbar/navbar.html'"></div>
<div ng-repreat="item in items">
<div class="item-page-container">
<div class="item-p-img">
{{item.name}}
</div>
<div class="item-p-tab-Container">
<ul>
<li>{{item.name}}</li>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
Please ask for any more code or for easier view, see my Github Repo
Please be clear on the function, feel free to put into a plunker, my Javascript skills come from Angular, but searching an array like this I haven't done before. I'd need a good solution where I can transfer/learn the logic.
Store View
(not sure about your routing) but would try smt like this:
<a ng-href="/items/{{item.itemID}}"><button role="button">More</button></a>
this should send you to your item view.
In your Item ctrl, if you inject $routeParams you could fetch the id like so:
item_id = $routeParams.id
and then search for your item like so:
items = StoreService.items();
$scope.item = items.indexOf(item_id)
so in your item view remove the ng-repeat and work with the item object.
As I said before, not enterily sure of your project's structures,. but this should get you on your way.
Make your routes like this :
$routeProvider
.when('/items', {
templateUrl: 'yourtemplate-path/items.html',
controller: 'yourItemController'
})
.when('/items/:itemId', {
templateUrl: 'yourtemplate-path/items-detail.html',
controller: 'yourItemDetailsController'
})
Your controller:
For items,
'use strict';
angular.module('angularStoreApp')
.controller('storeCtrl', function($scope, StoreService){
StoreService.items(function(){
$scope.items = data;
});
});
For item detail page,
'use strict';
angular.module('angularStoreApp')
.controller('storeDetailsCtrl', function($scope, $routeParams, StoreService){
StoreService.items({itemId: $routeParams.itemId}, function(){
$scope.item = data;
});
});
and create your new service, which fetches the data based on this id(itemId)
NOTE: I didn't tested the code.
I've been trying to figure this out for like 10 hours now. Time to ask for help!
I'm trying to pass a variable from an angular.js template variable to bootbox for a nice looking confirmation prompt.
Assume that I have the following (abbreviated for clarity):
<script>
$(document).on("click", ".confirm", (function(e) {
e.preventDefault();
bootbox.confirm("This needs to be the value of {{item.name}}", function(confirmed) {
console.log("Confirmed: "+confirmed);
});
}));
</script>
which is executed as such:
<ul class="list-group">
<li ng-repeat="item in items">
<span class="glyphicon glyphicon-fire red"></span>
</li>
</ul>
When the user clicks the link, I would like a the confirmation box to appear, and I need to include attributes like {{item.name}} and {{item.row}} that are specific to this element in the list.
I have read up on the $compile functionality of angular.js and I got it working in so far as having a <div compile="name"> but that doesn't help me for retrieving a single entry out of my list as I am iterating. Any help would be appreciated!
Applied as a directive...
HTML:
<body ng-app="myApp" ng-controller="MainController">
<ul class="list-group">
<li ng-repeat="item in items">
<confirm-button name="{{item.name}}"></confirm-button>
</li>
</ul>
</body>
JS:
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.items = [
{ name: 'one' },
{ name: 'two' },
{ name: 'three' }
];
})
.directive('confirmButton', function(){
return {
restrict: 'E',
scope: { name: '#' },
template: '<span class="glyphicon glyphicon-fire red" ng-click="confirm(name)">Button</span>',
controller: function($scope) {
$scope.confirm = function(name) {
bootbox.confirm("The name from $scope.items for this item is: " + name, function(result){
if (result) {
console.log('Confirmed!');
} else {
console.log('Cancelled');
}
});
};
}
}
});
Working plunk
This is a simple approach, but depending on what you're trying to do it may not suit you:
var app = angular.module('app', []);
app.controller('AppCtrl', function ($scope) {
$scope.items = [
{ name: "Bla bla bla bla?", url: "http://stackoverflow.com" },
{ name: "Ble ble ble ble?", url: "http://github.com" }
];
$scope.confirm = function (item) {
bootbox.confirm("Confirm?", function (confirmed) {
alert('Confirmed: '+ confirmed +'. Url: '+ item.url);
});
};
});
In your html:
<div ng-app='app' ng-controller="AppCtrl">
<ul class="list-group">
<li ng-repeat="item in items">
<a ng-click="confirm(item)">
<span class="glyphicon glyphicon-fire red"></span>
{{ item.name }}
</a>
</li>
</ul>
</div>
Depending on what you want, maybe you should check out the directives: https://docs.angularjs.org/guide/directive