http://plnkr.co/edit/pJRzKn2v1s865w5WZBkR?p=preview
I have a large select dropdown form which is repeated in 2 places. The only thing that changes is the first select tag, which has a different function.
<!--
On simple, change ng-change function to functionOne
On advanced, change ng-change function to functionTwo
-->
<select name="name1" ng-change="functionOne('function1')" id="the-id-1">
<select name="name2" ng-change="functionTwo('function2)" id="the-id-2">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
I tried using ng-hide ng-show however there must be a different way to accomplish this.
var app = angular.module('myApp', [])
.directive('termsForm', function() {
return {
templateUrl : "termsForm.html",
restrict : "E",
scope : false,
controller : 'TermsFormController'
}
})
.directive('selectOptions', function() {
return {
templateUrl : "form.html",
restrict : "E",
scope : false
}
})
.controller('TermsFormController',
['$scope',
function($scope) {
var vs = $scope;
vs.hello = "This is the form.";
vs.showingSimple = true;
vs.showingAdvanced = false;
vs.showForm = function(type) {
if (type === 'simple') {
vs.showingSimple = true;
vs.showingAdvanced = false;
} else if (type === 'advanced') {
vs.showingSimple = false;
vs.showingAdvanced = true;
}
}
vs.functionOne = function(msg) {
alert(msg);
}
vs.functionTwo = function(msg) {
alert(msg);
}
}]);
termsForm.html
<ul class="nav nav-tabs">
<button class="btn btn-info" ng-click="showForm('simple')">Simple</button>
<button class="btn btn-info" ng-click="showForm('advanced')">Advanced</button>
</ul>
<p>The select:</p>
<div ng-show="showingSimple" class="simple-form">
<p>Simple</p>
<select-options></select-options>
</div>
<div ng-show="showingAdvanced" class="advanced-form">
<p>Advanced</p>
<select-options></select-options>
</div>
You already have a directive created for your select, that gets you half way there. Now you just need to pass the function in through whats known as the isolated scope.
.directive('selectOptions', function() {
return {
templateUrl : "form.html",
restrict : "E",
scope : {
changeFunc: '&'
}
}
})
This allows you to pass in the function you want to call on the ng-change event:
<select-options changeFunc="function1"></select-options>
<select-options changeFunc="function2"></select-options>
And then in your form.html you simply put
<select name="name2" ng-change="changeFunc()" id="the-id-2">
This way you are basically passing the funciton in as a parameter. Read this blog for a great guide on isolated scopes.
I would just refactor your markup and controller to adapt based on the simple/advanced context.
In your controller, you'd expose a 'generic' on change function for the dropdown, first...
(function () {
'use strict';
angular.module('app').controller('someCtrl', [someCtrl]);
function someCtrl() {
var vm = this;
vm.isSimple = true;
vm.nameChange = function () {
if(vm.isSimple)
functionOne('function1');
else
functionTwo('function2');
}
// Other things go here.
}
})();
...Then, on your view, your select would change to this*:
<select id="someId" name="someName" ng-change="vm.nameChange()" />
*: Assuming you're using controllerAs syntax, that is. If you're not, don't prepend the vm. on the select.
Related
I did a conditional statement on the div on data-ng-class and I want to somehow add this scope to the controller and specify when the url is /vegetarian to apply class 'egg' and i manually change url i want the class 'bacon' to be applied, but its not working, where I have i gone wrong?
html:
<div data-ng-class="{'egg': isVeggie, 'bacon': !isVeggie }">
Text here
</div>
controller:
app.controller('foodCtrl', function ($scope, $location) {
$scope.location = $location;
$scope.isVeggie = false;
$scope.isVeggie = function() {
if(isVeggie === $location.path('/vegetarian')) {
return true;
}
}
});
this is not working. When I type /vegetarian, the class egg is being applied, but when I change the url to something else like /breakfast, the class 'egg' remains. How can I make this work?
Thanks
Why the property and the function with the same name ? After all you will have only the function
$scope.isVeggie = false;
$scope.isVeggie = function() {
if(isVeggie === $location.path('/vegetarian')) {
return true;
}
}
Change your code to have only the function.
Only
$scope.isVeggie = function() {
if(isVeggie === $location.path('/vegetarian')) {
return true;
}
}
and markup
<div data-ng-class="{'egg': isVeggie(), 'bacon': !isVeggie() }">
Text here
</div>
You bind you ng-class directive to the property isVeggie and not the function isVeggie().
Change your html to:
<div data-ng-class="{'egg': isVeggie(), 'bacon': !isVeggie() }">
Text here
</div>
You can then remove the following line in your controller:
$scope.isVeggie = false;
I am new to angular-js. I have two controllers (welcomeContoller,productController) and both handling the same model within the factory.
When the model getting updating by one controller(productController) it should reflect the update in another controller. (welcomeContoller)
But its not happening now.
HTML code :
<body ng-app="myApp">
<div ng-controller="welcomeContoller">
{{totalProductCnt}}
</div>
<div ng-controller="productController">
<div class="addRemoveCart">
<span class="pull-left glyphicon glyphicon-minus" ng-click="removeProduct()"></span>
<span class="pull-right glyphicon glyphicon-plus" ng-click="addProduct(1)"></span>
</div>
</div>
JS code
var myApp = angular.module("myApp", ['ui.bootstrap']);
myApp.factory("productCountFactory", function() {
return {
totalProducts:0
};
});
myApp.controller("welcomeContoller", function($scope, productCountFactory)
{
$scope.totalProductCnt = productCountFactory.totalProducts;
});
myApp.controller("productController", function($scope, productCountFactory) {
$scope.addProduct = function() {
productCountFactory.totalProducts++;
alert(productCountFactory.totalProducts);
};
$scope.removeProduct = function() {
if(productCountFactory.totalProducts >=1)
productCountFactory.totalProducts--;
alert(productCountFactory.totalProducts);
};
});
Even after the addProduct is called the totalProductCnt is displaying as zero. I want to display the value for each increment.
Plunkr Link
Put the factory object reference on scope:
myApp.controller("welcomeContoller", function($scope, productCountFactory) {
$scope.productCountFactory = productCountFactory;
});
Watch the property of the object.
{{productCountFactory.totalProducts}}
The DEMO on PLNKR.
By putting a reference on scope, on every digest cycle the watcher looks up the value of the property and updates the DOM if there is a change.
The totalProductCnt from your welcomeController isn't updated because it is assigned only once when the controller is created.
You can use several solutions to refresh the displayed value. Use a getter for your totalProducts in the factory :
myApp.factory("productCountFactory", function() {
var totalProducts = 0;
return {
getTotalProducts: function() {
return totalProducts;
},
addProduct: function() {
totalProducts++;
},
removeProduct: function() {
totalProducts--;
}
};
});
myApp.controller("welcomeContoller", function($scope, productCountFactory) {
$scope.getTotalProducts = productCountFactory.getTotalProducts;
});
myApp.controller("productController", function($scope, productCountFactory) {
$scope.addProduct = function() {
productCountFactory.addProduct();
};
$scope.removeProduct = function() {
if (productCountFactory.getTotalProducts() >= 1)
productCountFactory.removeProduct();
};
});
And update the view accordingly:
<div ng-controller="welcomeContoller">
{{getTotalProducts()}}
</div>
Plunkr Link
I have a page design in which i have attached the main controller to body:
<body ng-controller="firstController">
first
second
<input ng-model="hello" ng-disabled="xyz()">
<button id="test" ng-disabled="xyz()">test button</button>
{{hello}}
<div ng-view></div>
</body>
I load a template for default as
var mainApp = angular.module('mainApp',['ngRoute'])
.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/',{
templateUrl: 'partials/first.html',
controller: 'firstTemplate'
})
I my template i a check box as:
<div>
<input type="checkbox" ng-model="check">
</div>
Now i want the button #id to be disable the check box is unchecked, now i thought of using factory as these two are in different controllers:
mainApp.factory('clientId',function(){
var flag = true;
return flag;
});
mainApp.controller('firstController',['$scope','clientId',function($scope,clientId){
//$scope.check = true;
clientId.flag = false;
$scope.xyz = function(){
if(clientId){
return true;
}else{
return false;
}
}
}])
I am able to get the value from factory, now i want to update the value of the flag from different controller(template controller) and the value should reflect in first controller too so that the state of button can be updated.
mainApp.controller('firstTemplate',['$scope','clientId',function($scope,clientId){
}])
How can i update the value from second controller and make it reflect in first controller. If it is not possible is there and alternative to achieve this?
You can solve this using two ways.
1. using $rootScope.
2. using services.
using $rootScope:
<input ng-model="hello" ng-disabled="flagtoDisable">
<button id="test" ng-disabled="flagtoDisable">test button</button>
{{hello}}
<div ng-view></div>
mainApp.controller('firstController', ['$scope','$rootScope','clientId',function($scope,$rootScope,clientId){
//$scope.check = true;
clientId.flag = false;
$scope.xyz = function(){
if(clientId){
return true;
}else{
return false;
}
}
}])
mainApp.controller('firstTemplate','$scope','$rootScope','clientId',
function($scope,$rootScope,clientId){
$rootScope.flagtoDisable = false;
if($scope.check == true){
$rootScope.flagtoDisable = true;
}
}])
using Service:
mainApp.factory('clientId',function(){
var flag = {
status:false; };
return{
setFlag : funcion() {
flag.status = true;
}
getFlag : funcion() {
return flag;
}
});
mainApp.controller('firstController',['$scope','clientId',function($scope,clientId){
//$scope.check = true;
$scope.xyz = function(){
var flag = clientId.getFlag();
return flag.status;
}
}])
<input ng-model="hello" ng-disabled="xyz()">
<button id="test" ng-disabled="xyz()">test button</button>
{{hello}}
<div ng-view></div>
mainApp.controller('firstTemplate',['$scope','clientId',function($scope,clientId){
if($scope.check== true){
clientId.setFlag();
}
}])
This code is not tested.you can follow this approaches.
Yes, You can do it by using $rootScope
The ways are.
Initialize the $rootScope in your controller
Call the first controller scope variable from second controller
if 1st controller varaiable is $scope.name
now you just call $rootScope instead of $scope in second controller
like
$rootScope.name
I have a pop up screen in which a user require to select from two drop down lists.
After the selections were completed i return the selections to the service and save them in an object.
app.service('OriginalService', [ '$modal',
function ($modal) {
var that = this;
this.filtersMananger = { // my-ng-models for the two drop-down-lists
firstFilter: "",
secondFilter: ""
};
this.openDialog = function(){
var modalInstance = $modal.open({
templateUrl: 'ModalScreen.html',
controller: 'ModalController',
resolve: {
filtersManagerObject: function () {
return that.filtersMananger;
}
}
});
modalInstance.result.then(function (filtersMananger) {
that.filtersMananger.firstFilter = filtersMananger.selectedFirstFilter;
that.filtersMananger.secondFilter = filtersMananger.selectedSecondFilter;
}, function () {
});
};
}
]);
The pop up html:
<div class="data-filters-container">
<div class="data-filter">
<label for="filter-data-drop-down">FIRST FILTER</label>
<select name="filterDataDropDown" ng-model="filtersMananger.selectedFirstFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
</div>
<div class="data-filter col-xs-4">
<label for="filter-data-drop-down">SECOND FILTER</label>
<select name="filterDataDropDown" ng-model="filtersMananger.selectedSecondFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
</div>
However, this change is important and i have to call to the controller which knows many other services to send them information regarding this change.
In order to do it i used a watch function in the controller:
$scope.$watch('OriginalService.filtersMananger.firstFilter + OriginalService.filtersMananger.secondFilter', function (newVal, oldVal) {
if (newVal !== oldVal) {
DO SOME LOGIC
}
});
I compare between newVal and oldVal because when the app is uploaded the event is called and we enter to this function.
The problem is that the newVal is contains only the value of the secondVariable.
Is there any idea why the newVal is not contains also the first variable?
Use $watchCollection:
$scope.$watchCollection('[serviceName.Object.firstVariable,serviceName.Object.secondVariable]', function (newValues, oldValues) {
});
Or if you're using angular 1.3 use $watchGroup:
$scope.$watchGroup(['serviceName.Object.firstVariable','serviceName.Object.secondVariable'],function(newValues, oldValues){
})
You could also use ng-change on your select.
The ng-change will call a function that do your logic
<div class="data-filters-container">
<div class="data-filter">
<label for="filter-data-drop-down">FIRST FILTER</label>
<select name="filterDataDropDown" ng-change="checkFilterOne()" ng-model="filtersMananger.selectedFirstFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
</div>
<div class="data-filter col-xs-4">
<label for="filter-data-drop-down">SECOND FILTER</label>
<select name="filterDataDropDown" ng-change="checkFilterTwo()" ng-model="filtersMananger.selectedSecondFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
</div>
It will call the function when your model will change that is like a $watch.
I am having a lot of trouble trying to save values from the modal component available in Angular UI.
Here is the page controller that calls the modal dialog
$scope.sourceSchema = [];
$scope.targetSchema = [];
$scope.apiDefinition = [];
$scope.availableSchemas = availableSchemas.get();
$scope.addComponent = function (type) {
$scope.$broadcast('addComponent', [type]);
var templateUrl = "";
var controller = null;
var resolve = null;
var componentSchema = [];
switch (type) {
case "sourceSchema":
templateUrl = 'source-schema.tpl.html';
controller = 'SourceCtrl';
componentSchema = $scope.sourceSchema;
break;
case "targetSchema":
templateUrl = 'target-schema.tpl.html';
controller = 'TargetCtrl';
componentSchema = $scope.targetSchema;
break;
case "api":
templateUrl = 'api.tpl.html';
controller = 'SourceCtrl';
componentSchema = $scope.apiDefinition;
break;
}
var modalInstance = $modal.open({
templateUrl: templateUrl,
controller: controller,
resolve: {
existingSchemas: function () {
return $scope.availableSchemas;
}
}
});
modalInstance.result.then(function (selectedItem) {
componentSchema.push(selectedItem);
}, function () {
// $log.info('Modal dismissed at: ' + new Date());
});
};
Here is the SourceCtrl that controls one of the modal dialogs I am using:
.controller("SourceCtrl", function ($scope, $modalInstance, existingSchemas) {
$scope.existingSchemas = existingSchemas;
$scope.sourceSchema = "";
$scope.ok = function () {
$modalInstance.close($scope.sourceSchema);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.$watch('sourceSchema', function(newValue, oldValue) {
console.log(newValue, oldValue);
})
})
And finally here is the template for this controller (SourceCtrl).
<div class="modal-header">
<h3>New Source Schema</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-3">
<label for="schema-source">Source</label>
</div>
<div class="col-xs-9">
<select name="sourceSchema" ng-model="sourceSchema" ng-options="s as s.name for s in existingSchemas">
<option value="">-- choose source --</option>
</select>
</div>
<h5>Name: {{sourceSchema.name}}</h5>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
The funny thing is that when I change the value in the select, the {{sourceSchema.name}} line does show the correct name of the schema, however the changes do not get reflected in the controller and the actual value is not being passed on. I have used a watch to detect when something gets changed and apparently it doesn't. But the value does get changed otherwise why would it get displayed when I select it in the dropdown list.
Make sure that you've got a dot in your ngModel expression - that is - that you are binding to an object property and not directly to the scope. Something like:
.controller("SourceCtrl", function ($scope, $modalInstance, existingSchemas) {
$scope.existingSchemas = existingSchemas;
$scope.source = {
schema: ''
};
$scope.ok = function () {
$modalInstance.close($scope.source.schema);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.$watch('source.schema', function(newValue, oldValue) {
console.log(newValue, oldValue);
})
})
And then, in your markup:
<select name="sourceSchema" ng-model="source.schema" ng-options="s as s.name for s in existingSchemas">
<option value="">-- choose source --</option>
</select>
If you can provide a plunker I can help you fixing the code.