I'm having trouble understanding some of the basics. Here are 2 controllers I have:
<form ng-controller="NewList" id="form" ng-submit="submit()">
<input name="title" ng-model="formData.title" placeholder="{{placeholders.title}}" />
<button type="submit">Generate</button>
<p ng-show="loading == 1">Loading...</p>
<p ng-show="loading == 2">Response: {{response}}</p>
</form>
<div id="lists" ng-controller="GetLists">
<ul>
<li ng-show="loading">Loading...</li>
<li class="list" ng-repeat="list in lists">
<b>{{list.id}}</b> : {{list.title}}
</li>
</ul>
</div>
JS:
function NewList($scope, $http) {
$scope.formData = { };
$scope.placeholders = { "title" : "List title" };
$scope.loading = 0;
$scope.submit = function() {
$scope.loading = 1;
$http.post(window.apiBase + 'lists/create', this.formData)
.success(function(response) {
$scope.response = response;
$scope.loading = 2;
});
}
}
function GetLists($scope, $http) {
$scope.loading = true;
$http.get(window.apiBase + 'lists/all').success(function(response) {
$scope.lists = response.lists;
$scope.loading = false
});
}
What I'm trying to achieve, is upon form submit, refresh the lists. Meaning, when .success() hits in NewList, call GetList and make it happen again. How do I achieve this?
Related
I am trying to do an edit field in angular js but I don't know how to do that one help me
below is my Crud operation code
var app = angular.module('myApp', [])
app.controller('myCtrl', ['$scope', function($scope) {
$scope.products = ["venu", "balaji", "suresh"];
$scope.addItem = function() {
$scope.errortext = "";
if (!$scope.addMe) {
return;
}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe)
} else {
$scope.errortext = "The item is already in your names list.";
}
}
$scope.removeItem = function(x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}<span ng-click="removeItem($index)">×</span>
</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">ADD</button>
<p>{{errortext}}</p>
<p>Try to add the same name twice, and you will get an error message.</p>
</div>
</div>
I am doing crud operations in angular js. i have done Delete and Add but I dont know how to do Edit operation in angular js
var app = angular.module('myApp', [])
app.controller('myCtrl', ['$scope', function($scope) {
$scope.products = ["venu", "balaji", "suresh"];
$scope.addItem = function() {
$scope.errortext = "";
if (!$scope.addMe) {
return;
}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe)
} else {
$scope.errortext = "The item is already in your names list.";
}
$scope.addMe = "";
}
$scope.removeItem = function(x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
$scope.edit = function(index){
$scope.addMe = $scope.products[index];
$scope.products.splice(index, 1);
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}
<span ng-click="removeItem($index)">×</span>
<span style="color:blue;cursor:pointer;" ng-click="edit($index)">Edit</span>
</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">ADD</button>
<p>{{errortext}}</p>
<p>Try to add the same name twice, and you will get an error message.</p>
</div>
</div>
Try this.
The solution is here:
HTML
<li ng-repeat="x in products" ng-click="preEdit(x, $index)">{{x}}<span ng-click="removeItem($index)">×</span></li>
<input ng-model="addMe">
<button ng-if="isAdd" ng-click="addItem()">ADD</button>
<button ng-if="!isAdd" ng-click="editItem()">EDIT</button>
JS
$scope.isAdd = true;
$scope.preEdit = preEdit;
var index = '';
function preEdit(x, i){
$scope.addMe = x;
index = i;
$scope.isAdd = false;
}
$scope.editItem = editItem ;
function editItem (){
$scope.products[index] = $scope.addMe;
$scope.isAdd = true;
$scope.addMe = '';
index = '';
}
Look my solution in filddle: https://jsfiddle.net/tfx8njw6/
At first you need to add a edit option on the <li> say,
<ul>
<li ng-repeat="x in products">{{x}}
<span ng-click="removeItem($index)">×</span>
<span ng-click="editItem($index)">Edit</span>
</li>
</ul>
Then add a controller function for edit editItem() like
$scope.editItem= function(index) {
$scope.addMe = $scope.products[index];
//this variable will allow you to check whether the operation is an edit or add
$scope.editIndex = index;
}
You can then reuse your addItem() function like this
$scope.addItem = function() {
$scope.errortext = "";
if (!$scope.addMe) {
return;
}
if(angular.isDefined($scope.editIndex)){
$scope.products[$scope.editIndex] = $scope.addMe;
//reset the variable to undefined after using it
$scope.editIndex = undefined;
}else{
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your names list.";
}
}
}
If you want to take it to the "next level", check out xeditable. :)
https://vitalets.github.io/angular-xeditable/#text-simple
Good luck!
For Edit what you can do:
0.Pass the id on edit click and get data of that id and assign to the same variable you have used for add and hide add button and show update button.
1.Either use the same text field which you are using for add and show/hide button add/update accordingly.
2.You can use separately div which includes one text box and button to update.Show/hide as per you action.
Here i am using angular service.In my case i am getting value for first app but not for second .please help me .
thank you.
here is my html:-
<div ng-app="mainApp" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="multiply()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<div ng-app="myApp2" ng-controller="myController2">
<p>Enter a number: <input type="number" ng-model="numberSecond" />
<button ng-click="multiplyValue()">X<sup>2</sup></button>
<p>Result: {{result2}}</p>
</div>
here is js:-
angular.module('myReuseableMod',[]).factory('$myReuseableSrvc',function()
{
// code here
var factory = {};
factory.multiply = function(a)
{
return a * a
}
return factory;
});
var mainApp = angular.module("mainApp", ['myReuseableMod']);
mainApp.controller('CalcController',['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
alert("inside controller");
$scope.multiply = function()
{
alert("hello1");
$scope.result = $myReuseableSrvc.multiply($scope.number);
}
}]);
var mainApp2 = angular.module("myApp2", ['myReuseableMod']);
mainApp.controller('myController2',['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
alert("inside controller");
$scope.multiplyValue = function()
{
alert("hello1");
$scope.result2 = $myReuseableSrvc.multiply($scope.numberSecond);
}
}]);
Your 'myController2' is in the wrong app
mainApp.controller('myController2'
Should be:
mainApp2.controller('myController2'
EDIT:
Ah yes I see the problem. You cannot use ng-app twice like that. If you want what you are trying to achieve which is multiple applications you have to 'bootstrap' the second one:
plunk here:
http://plnkr.co/edit/qfllLO9uy6bC5OLkHnYZ?p=preview
angular.module('myReuseableMod',[]).factory('$myReuseableSrvc',function() {
var factory = {};
factory.multiply = function(a) {
return a * a
}
return factory;
});
var mainApp = angular.module("mainApp", ["myReuseableMod"]);
mainApp.controller('CalcController', ['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
$scope.multiply = function() {
$scope.result = $myReuseableSrvc.multiply($scope.number);
}
}]);
var mainApp2 = angular.module("mainApp2", []);
mainApp2.controller("MyController2", function($scope, $myReuseableSrvc) {
console.log('init B');
$scope.multiplyValue = function() {
$scope.result2 = $myReuseableSrvc.multiply($scope.numberSecond);
}
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("myDiv2"), ["mainApp2", "myReuseableMod"]);
});
This is a good post to read:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
I have 2 controllers. I want to make a simple toggle where if a function is called it hides code in the other controller. Here is what I have...
Angular:
var app = angular.module('plunker', []);
app.factory('data', function () {
var fac = [];
fac.hideIt = function (hide) {
console.log(hide)
if (hide != null)
return true;
else
return false;
};
return fac;
});
app.controller('MainCtrl', function($scope, data) {
$scope.name = 'World';
console.log(data.hideIt()); //its false
$scope.hide = data.hideIt();
});
app.controller('SecCtrl', function($scope, data) {
$scope.hideAbove = function () {
var hide = true;
data.hideIt(hide);
console.log(data.hideIt(hide)) //now it is true
}
});
HTML:
<div ng-controller="MainCtrl">
<div ng-if="hide == false">
<p>Hello {{name}}!</p>
</div>
</div>
<div ng-controller="SecCtrl">
<div ng-click="hideAbove()">CLICK HERE </div>
</div>
Link to Plunkr:
http://plnkr.co/edit/zOAf5vGMTAd8A10NGiS1?p=preview
Is there no way to use a controller to hide code that is in another controller?
You dont need to use $emit, $rootScope.$broadcast or something else
in your code you asked to the factory the value of a local variable, you cant updates it because each time you start the method a new variable was created;
Here is a working example, hope it will help you
http://plnkr.co/edit/jBc3DJnzXNJUiVVwRAPw?p=preview
The factory declare some useful methods like updates and gets hide value
app.factory('HideFactory', function () {
var prototype = {};
var hide = false;
prototype.getDisplayMode = function() {
return hide;
}
prototype.hideIt = function (val) {
hide = typeof val == 'boolean' ? val : false;
return val;
};
return prototype;
});
The controllers declare some variables which are a reference to the factory methods
app.controller('MainCtrl', ['$scope', 'HideFactory',function($scope, HideFactory) {
$scope.name = 'World';
$scope.isHide = HideFactory.getDisplayMode;
}]);
app.controller('SecCtrl', ['$scope', 'HideFactory', function($scope, HideFactory) {
$scope.isHide = HideFactory.getDisplayMode;
$scope.hideAbove = function() {
HideFactory.hideIt(true);
}
}]);
And the html, the ng-if directive call the isHide method, linked to the getDisplayMode method of the factory
<body>
<div ng-controller="MainCtrl">
<div ng-if="!isHide()">
<p>Hello {{name}}!</p>
</div>
</div>
<div ng-controller="SecCtrl">
<div ng-click="hideAbove()">CLICK HERE </div>
</div>
</body>
You're about halfway there with your factory, you have most of a setter but not a getter. Here's what I'd change.
Factory:
app.factory('data', function () {
var fac = [];
var state = false;
fac.hideIt = function (hide) {
state = hide;
};
fac.hidden = function() {
return state;
}
return fac;
});
Controller:
app.controller('MainCtrl', function($scope, data) {
$scope.name = 'World';
$scope.hide = data.hidden;
});
HTML:
<div ng-controller="MainCtrl">
<div ng-hide="hide()">
<p>Hello {{name}}!</p>
</div>
</div>
Forked Plunker
please see here: http://plnkr.co/edit/3NEErc0zUpXlb1LarXar?p=preview
var app = angular.module('plunker', []);
app.factory('data', function() {
var fac = [];
var _hide = {};
hideIt = function(hide) {
console.log("from fact " + hide)
if (hide !== null) {
_hide.state = true;
return _hide;
} else
_hide.state = false;
return _hide;
};
return {
fac: fac,
hideIt: hideIt,
hide: _hide
};
});
app.controller('MainCtrl', function($scope, data) {
$scope.name = 'World';
//console.log(data.hideIt()); //its false
$scope.hide = data.hide;
});
app.controller('SecCtrl', function($scope, data) {
$scope.hideAbove = function() {
var hide = true;
data.hideIt(hide);
}
});
HTML:
<div ng-if="hide.state != true">
<p>Hello {{name}}!</p>
</div>
</div>
<div ng-controller="SecCtrl">
<div ng-click="hideAbove()">CLICK HERE</div>
</div>
</body>
You want to use $emit.
function firstCtrl($scope){
$scope.$on('someEvent', function(event, data) { console.log(data); });
}
function secondCtrl($scope){
$scope.$emit('someEvent', [1,2,3]);
}
I've created a ASP.NET MVC 4 project by using Angular JS. I wouldn't be able to create a JSFiddle for this example of code.
I notice that I retrieve well the categories and it prints well. Then, when I click on one of the categories represented by a tag '<a>', my code goes to $scope.setActualItem of my app.js and the ajax call retrieves the right datas. But the changes are not printed in my view. However, I use "<div ng-repeat="p in products">" to get datas from the controller.
Do you have a solution ?
Thank you
app.js :
var appli = angular.module("Demo", []);
appli.controller('CategoryCtrl', function ($scope, $http) {
$http.get('/Category/GetCategories')
.success(
function (data) {
console.log(data);
$scope.categories = data;
}
);
$scope.setActualItem = function (index) {
$scope.currentItem = $scope.categories[index];
var idCat = $scope.currentItem.id;
console.log("passe ici");
$http.get('/Category/GetProductsByCategory/'+idCat)
.success(
function (data) {
console.log(data);
$scope.products = data;
}
);
};
});
My View :
<html ng-app="Demo">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script src="~/Scripts/app.js"></script>
</head>
<body ng-controller="CategoryCtrl">
#Html.Partial("~/Views/Header/Index.cshtml")
<div class="col-lg-3 col-md-3 col-sm-12">
<div class="col-lg-12 col-md-12 col-sm-6">
<div class="no-padding">
<span class="title" style="padding-top: 20px;">CATEGORIES</span>
</div>
<a class ="list-group-item" ng-click="setActualItem($index)" ng-repeat="cat in categories">{{cat.name}}</a>
</div>
</div>
<div id="ProductListcategory">
ggfgfgfgfgf
<div ng-repeat="p in products">
<label>{{p.id}}</label>
<label>{{p.name}}</label>
</div>
</div>
</body>
</html>
Use angular.copy and define $scope.products on begining
var appli = angular.module("Demo", []);
appli.controller('CategoryCtrl', function ($scope, $http) {
$scope.products = [];
$http.get('/Category/GetCategories')
.success(
function (data) {
console.log(data);
$scope.categories = data;
}
);
$scope.setActualItem = function (index) {
$scope.currentItem = $scope.categories[index];
var idCat = $scope.currentItem.id;
console.log("passe ici");
$http.get('/Category/GetProductsByCategory/'+idCat)
.success(
function (data) {
console.log(data);
angular.copy(data,$scope.products);
//or angular.copy(data.data, $scope.products);
}
);
};
});
MainController.js
app.controller("mainController", function($scope, $http){
$scope.movies = [];
$scope.searchFilter = '';
$scope.init = function() {
};
$scope.getMovies = function(){
var movieName = $('#MovieName').val();
var movies = getMovies(movieName); // Gets json
$scope.parseMovies(movies);
};
$scope.parseMovies = function(movies){
$scope.movies = [];
$.each(movies, function( index, value ) {
$scope.movies.push($scope.createMovie(value));
});
};
$scope.createMovie = function(json){
Movie=new Object();
Movie.id=json.id;
Movie.title=json.title;
Movie.year=json.year;
Movie.runtime=json.runtime;
return Movie;
};
});
app.js
var app = angular.module('MoviesApp',[]);
html
<body ng-controller="MovieListCtrl">
<div class="container main-frame" ng-app="MoviesApp" ng-controller="mainController">
<input type="text" id="MovieName" />
<input type="button" data-ng-click="getMovies()" />
<ul>
<li ng-repeat="movie in movies">
{{movie.title}}
</li>
</ul>
</div>
</body>
When I click the button and getMovies() is called the data is retrieved ok but the template does not get filled. Only when I click the button again does it get filled.
The thing is when it is clicked the second time, the template gets filled before the new json is retrieved (I put a breakpoint in the script).
I'm stuck