It's an edit form with parent record first populated then dependent select list is populated, and then it's expected the value from parent record pre-select the combo box.
html
<select ng-model="data.trackId" >
<option ng-repeat="track in tracks" value="{{track.id}}">{{track.name}}</option>
initial result once parent record is pulled.
if(data) {
this.$scope.data.id = data.id;
this.$scope.data.name = data.name;
this.$scope.data.room = data.room;
this.$scope.data.start = data.start;
this.$scope.data.end = data.end;
this.$scope.data.dayId = data.day_id;
this.$scope.data.trackId = data.track_id;
this.$scope.data.color = data.color;
this.$scope.data.description = data.description;
this.$scope.$apply();
this.$element[0].removeAttribute("style");
}
//later track results were pulled
trackResult: function(data, status, headers, config) {
for(var i=0; i<data.length; i++) {
this.$scope.tracks.push(data[i]);
}
this.$scope.$apply();
},
Problem:
List gets populated from the second call trackResult but default value from the $scope.trackId never sets the combo box to a value.
Edit: Controller Body
controller: function($scope, $element) {
var self = this;
this.$scope = $scope;
this.$element = $element;
this.$scope.data = {};
this.$scope.days = [];
this.$scope.tracks = [];
this.$scope.submit = function() {self.submit()};
this.$scope.cancel = function() {self.cancel()};
},
Edit : Updated with setting the data from outside the scope (OP request)
Use ng-options & ng-model
this is how i think it should be done in angularjs.
use the built in databinding capabilities to simplify your code and make it less complicated
for binding a list into a <select> and controlling the selected item, this snippet below should do the trick.
http://jsfiddle.net/72em40j4/
js
var myapp = angular.module('myapp', []);
myapp.controller('Ctrl', function ($scope) {
$scope.options = [];
$scope.selectedOption = null;
});
html
<script>
function clickFromOutside() {
var controllerElement = document.getElementById('container');
var controllerScope = angular.element(controllerElement).scope();
var firstTrack = {
id: 1,
first: 'First',
last: 'Track'
};
var secondTrack = {
id: 2,
first: 'Second',
last: 'Track'
};
controllerScope.options.push(firstTrack);
controllerScope.options.push(secondTrack);
controllerScope.selectedOption = secondTrack;
controllerScope.$apply();
}
</script>
<button onclick="clickFromOutside();">outside</button>
<div ng-app="myapp">
<fieldset id="container" ng-controller="Ctrl">
<select ng-options="p.first + ' ' + p.last for p in options" ng-model="selectedOption"></select> <pre>{{ selectedOption }}</pre>
</fieldset>
</div>
Related
I have a tooltip which popups on focus using angular popovers. What I need to do is when I click a button, to change it to popup on blur. It changes but doesn't change the tooltip behavior.
Here is the plunkr: http://plnkr.co/edit/L1oeZQrQdF0AdJMKVsG6?p=preview
Below is the code:
<input type="text"
ng-model="value"
value="{{value}}"
uib-popover-template="htmlPopover"
popover-trigger="{{triggerOn}}"
popover-popup-close-delay="1000"
class="form-control">
<script type="text/ng-template" id="myPopoverTemplate.html">
<div>
<button ng-click="test()"><b style="color: red">Add message</b></button>
</div>
</script>
controller
function ($scope) {
$scope.value = "Click me!";
$scope.dynamicPopover = {
content: 'Hello, World!',
templateUrl: 'myPopoverTemplate.html',
title: 'Title'
};
$scope.message = 'Trigger: none';
$scope.triggerOn = "focus";
$scope.changeTrigger = function(){
$scope.triggerOn = "blur";
$scope.message = "Should trigger on blur";
}
$scope.test = function(){
$scope.value = "test me click";
}
$scope.htmlPopover = 'myPopoverTemplate.html';
});
Looking at the source code for the uib-popover directive, one can that the triggers are set when the directive is linked.
compile: function(tElem, tAttrs) {
var tooltipLinker = $compile(template);
return function link(scope, element, attrs, tooltipCtrl) {
var tooltip;
var tooltipLinkedScope;
var transitionTimeout;
var showTimeout;
var hideTimeout;
var positionTimeout;
var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false;
//TRIGGERS SET AT LINK TIME
var triggers = getTriggers(undefined);
var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']);
var ttScope = scope.$new(true);
var repositionScheduled = false;
var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false;
var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false;
var observers = [];
var lastPlacement;
If one wants to change how the directive triggers, the directive needs to be re-compiled with the $compile service on each change to the triggers.
I am newer in anguler and want a value on change from select option and want to update status of particular ID. I have setup some code but this is not working. can you help me.
fetch data and get it on data and after that setup a select box
<select ng-model="newStatus" ng-change="changeNewStatus(data.id, data.message_status)">
<option value="1" ng-selected="data.message_status == 1">New</option>
<option value="2" ng-selected="data.message_status == 2">Closed</option>
</select>
now i want to print it here {{selectedResult}}
below is my controller where i want to call this function
app.controller('MessageFetchGrid', function ($scope, $http, $timeout) {
$scope.changeNewStatus = function(msgId, msgStatus){
$scope.selectedResult = "msg-id="+msgId+" status= "+msgStatus;
}
});
here is my full code
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.controller('MessageFetchGrid', function ($scope, $http, $timeout) {
$http.get('api/v1/loadMessage.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 25; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
$scope.changeNewStatus = function(msgId, msgStatus){
$scope.selectedResult = "msg-id="+msgId+" status= "+msgStatus;
}
});
you can use ng-options directive :
partial:
<div ng-app="test">
<div ng-controller="TestController">
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected">
<option value="">Select</optipn>
</select>
<span>{{selected}}</span>
</div>
</div>
js:
var app = angular.module("test", []);
app.controller("TestController", ["$scope", function($scope) {
$scope.items = [{
id: 1,
label: 'aLabel'
}, {
id: 2,
label: 'bLabel'
}];
}]);
example
http://codepen.io/anon/pen/MaRMPz
I am trying to add an object to the existing list. here is my code.
In controller:
$scope.itemList = [];
$scope.itemList = function () {
return itemService.getItemList();
};
getItemList read from a jason file locally not from service. now I am trying to add new object to this list.
here is my view:
<div>
<img src="/icon1.png" ng-click="sendNewItem()">
<input type="text" ng-model="itemtosend.itemName"/>
<input type="text" ng-model="itemtosend.itemNo"/>
</div>
In controller:
$scope.sendNewItem = function(){
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
$scope.itemList = $scope.itemList.push(newItem)
}
but Iam getting push is not a function. how to add the new object to the existing itemList?
You have many problems in your code :
//You define itemList as an Array (so you can push() in it)
$scope.itemList = [];
//But you redefine it as a function (you cannot push() to a function, ofc..
$scope.itemList = function () {
return itemService.getItemList();
};
then :
$scope.sendNewItem = function(){
//you say newItem is a function, but I guess what you want is an object
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
//$scope.itemList.push(newItem) is enough, no need for list = list.push("b")
$scope.itemList = $scope.itemList.push(newItem)
}
What you should have is :
In controller:
$scope.itemList = [];
$scope.sendNewItem = function(){
var newItem = {
itemName : $scope.itemtosend.itemName,
itenNo : $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
Please find bellow a code snippet :
var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
$scope.itemList = [];
$scope.sendNewItem = function() {
var newItem = {
name: $scope.itemtosend.itemName,
no: $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="Ctrl">
<label>Name :</label><input type="text" ng-model="itemtosend.itemName" />
<label>No :</label><input type="text" ng-model="itemtosend.itemNo" />
<button ng-click="sendNewItem()">Add</button>
<h3>Item List :</h3>
<div ng-repeat="item in itemList">
name : {{item.name}}, num : {{item.no}}
</div>
</div>
I have select list i set default option to be chosen. what happen is for few second it works then it disappear and the blank option in the list is chosen as default.
<div class="form-group">
<select class="form-control" ng-model="item.action" ng-options="option.value as option.title for option in options">
</select>
</div>
i want to set defualt option to be chosen :
so my controller look like this:
$scope.item = {};
$scope.options = [{
title: 'On entering',
value: 'enter'
}, {
title: 'On exiting',
value: 'exit'
}];
$scope.item.action= $scope.options[0].value;
$scope.profile = me.getUser();
$scope.profile.then(
function(user) {
$scope.owner = user;
$scope.item = {};
$scope.item.data = '';
$scope.item.published = true;
$scope.item.action= $scope.action;
$scope.item.owner = $scope.owner.displayName;
},
function(response) {
console.log(response);
}
);
me is a service that fecth the user data.
the reason why am defining $scope.item = {}; again is because i can't apend the displayName to the $scope.item out of the scope.
I commented this part of the code and it works well:
$scope.profile = me.getUser();
$scope.profile.then(
function(user) {
$scope.owner = user;
$scope.item = {};
$scope.item.data = '';
$scope.item.published = true;
$scope.item.action= $scope.action;
$scope.item.owner = $scope.owner.displayName;
},
function(response) {
console.log(response);
}
);
But now i can't figure out how to build my item object to send it in HTTP request
I want to recover my data from one controller to another, knowing that I change my view, let me explain I have my roads, for each road I have a controller, I managed to passed the data controller to another but I have to be on the right view. my first check my data recovered via ng-click on a dropdown and he goes to the other controller, the problem that when I'm on the right sight it works but if I'm on another view I select an item and I spend on the right view, nothing happens
var routeAppControllers = angular.module('routeAppControllers', []);
// Sharing Data of venues Between Controllers
routeApp.factory('mySharedService', function ($rootScope) {
var sharedService = {};
sharedService.venues = '';
sharedService.prepForBroadcast = function(venues){
this.venues = venues;
this.broadcastItem();
};
sharedService.broadcastItem = function(){
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
routeAppControllers.controller('GlobalController', ['$scope','$http','mySharedService', function GlobalController($scope, $http, mySharedService)
{
var venuesName = [];
$http.get('/ajax/venuesNameClient').success(function(data){
angular.forEach(data, function(value,key){
venuesName.push({name : value});
});
$scope.venuesName = venuesName
});
$scope.venueName = {};
var venues = [];
$scope.go = function(name) {
$http.get('/ajax/venuesClient').success(function(data){
angular.forEach(data, function(value,key){
if (value != "ok") {
for (var i=0;i<value.name.length;i=i+1)
{
if (value['name'][i] == name)
{
venues = [];
venues.push(value['name'][i]);
venues.push(value['email'][i]);
venues.push(value['address'][i]);
venues.push(value['long_description'][i]);
venues.push(value['creation_date'][i]);
venues.push(value['wifi_network'][i]);
}
}
};
});
mySharedService.prepForBroadcast(venues);
});
}
$scope.$on('handleBroadcast', function() {
$scope.venues = mySharedService.venues;
});
}
]);
// WelcomeController
routeAppControllers.controller('WelcomeController', ['$scope','mySharedService', function WelcomeController($scope, mySharedService)
{
$scope.$on('handleBroadcast', function() {
$scope.venues = mySharedService.venues;
console.log($scope.venues);
});
}
]);
<ui-select ng-model="venueName.selected" theme="select2" ng-disabled="disabled" style="min-width: 300px; padding-top:10px;">
<ui-select-match placeholder="Select a venue in the list ...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="venueName in venuesName | propsFilter: {name: $select.search}">
<div ng-click='go(venueName.name)'>{{venueName.name}}</div>
</ui-select-choices>
</ui-select>
any help please, this code work but i have to be in the right view
The Angular way to store and pass data between controllers and directives is to use services. As the services are singletons the store the data and can be injected into both directives and controllers.