I'm trying to add some text to the last cursor place after clicking a button.
In the controller:
$scope.addEmoji = function(name){
var element = $("#chat-msg-input-field");
element.focus(); //ie
var selection = element.getSelection();
var textBefore = $scope.chatMsg.substr(0, selection.start);
var textAfter = $scope.chatMsg.substr(selection.end);
$scope.chatMsg = textBefore + name + textAfter;
}
$scope.updateChatMsg = function(chatMsg){
$scope.chatMsg = chatMsg;
}
$scope.sendChatMsg = function(){
var backend = $scope.convs[$scope.active.conv].backend.name;
$scope.view.addChatMsg($scope.active.conv, $scope.active.user, $scope.chatMsg,new Date().getTime() / 1000, backend);
Chat[backend].on.sendChatMsg($scope.active.conv, $scope.chatMsg);
$scope.chatMsg = '';
};
And then some HTML:
<div class="chat-msg-button" >
<button ng-click="view.toggle('emojiContainer')" ><img src="/apps/chat/img/emoji/smile.png"></button>
</div>
<form id="chat-msg-form" ng-submit="sendChatMsg()">
<div class="chat-msg-button" >
<button type="submit"><div class="icon-play"> </div></button>
</div>
<div id="chat-msg-input">
<textarea id="chat-msg-input-field" autocomplete="off" type="text" ng-model="chatMsg" ng-change="updateChatMsg(chatMsg)" placeholder="Chat message"></textarea>
<div>{{ chatMsg }}</div>
</div>
</form>
What I'm trying to achieve: a user types some text in the textarea => $scope.chatMsg gets the value of the textarea. Now the user press one of the button's => the name of the button is added to the latest cursor position. (it's no problem to find the latest cursor position)
The problem
There is a difference between the value of $scope.chatMsg, {{ chatMsg }} inside the div and the text in the textarea.
The contents of the textarea and the div stays always the same. But when pressing the button the name is added to $scope.chatMsg but the contents of the textarea isn't changed...
How can I solve this?
TIA
First of all, you're mixing jQuery with AngularJS, it doesn't look like you need jQuery here that much.
Also, your chat message is updated in 3 different functions, so you need some debugging to see which are fired.
In general:
To solve your issue, try some more debugging, do a
$scope.$watch($scope.chatMsg, function(){
console.log($scope.chatMsg);
});
this will watch all changes to chatMsg. Add console.log() to each of your functions and you can watch which is fired.
Also, rather than using {{ }} inside your div just use ng-bind since that text is the only item in your div, it's cleaner if your app crashes somewhere.
// change from
<div>{{ chatMsg }}</div>
// to
<div ng-bind="chatMsg "></div>
Update: after seeing your plunker, I modified it and came up with this: http://plnkr.co/edit/oNKGxRrcweiJafKCm9A5?p=preview
Your ng-repeat needs to be tracked by $index so that duplicates are displayed rather than crashing when someone creates the same message
I solved all problems. The plunkr form above works. So after investigating all scopes with the Angular chrome extension I saw that chatMsg was defined in another scope. Thus not in the scope I was trying to acces it from.
Via this question angularJS ng-model input type number to rootScope not updating I found a solution.
I added chatMsg to the fields object.
Related
I'm trying to update models from a JSON representation of an object to a form. Here's a link to an example
To recreate my issue,
Change the data in the form (see that the JSON changes).
Change the JSON (See that the form doesn't change).
Here's my code:
JS
var ppl = {
createdby: "foo",
dateCreated: "bar",
}
angular.module('myApp', [])
.controller("Ctrl_List", function($scope) {
$scope.people = ppl
$scope.print = JSON.stringify($scope.ppl)
})
HTML
<div ng-app="myApp">
<div class="container" ng-controller="Ctrl_List">
<!-- FORM -->
<div class="row" ng-repeat="(key,val) in people track by $index">
<div class="col-md-12">
<label for="{{key}}">{{key}}</label>
<input class=form-control" id="{{key}}" ng-model="people[key]">
</div>
</div>
<!-- JSON -->
<div class="editable" contenteditable="true" ng-model="people">{{people}}</div>
</div>
</div>
When a user changes the JSON, the form should update in real-time.
Here's some things I have tried:
Change the JSON display element from div to input but it prints [Object][Object]
Also <input ng-model="JSON.stringify(people)"> but I get an "unbindable element" error.
Also tried adding a new model: $scope.print = JSON.stringify(people) but it shows nothing in the raw output.
Is it even possible to update a live object or am I gonna have to do some sort of event that triggers the form to change?
PS: Angular 1.5.8
There are several reasons why this doesn't work:
ng-model on a div doesn't do anything
even if it did, it would save a string to people, and your form would thus not work anymore.
You should use a textarea to make it work, and bind it to another variable, of type string. Using ng-change on the textarea, and on the inputs of the form, allows populating the people object by parsing the JSON string, and vice-verse, populating the JSON string from the people object.
See https://codepen.io/anon/pen/peexPG for a demo.
Refering to Contenteditable with ng-model doesn't work,
contenteditable tag will not work directly with angular's ng-model because the way contenteditable rerender the dom element on every change.
I'm very very new to Angular JS and have the following requirement:
I have an ng-repeat as shown below:
<div class="panel" ng-repeat="(appname, value) in chart.accordionData" style="margin-top: 0;">
<div class="accordion collapsed" data-parent="#accordion1"
data-toggle="collapse"
data-target="#{{appname.replace(' ','')}}">
<div class="accordion-head" initial-select index="{{$index}}">
<div class="arrow chevron"></div>
<h4><i></i>{{appname}}</h4>
</div>
</div>
<div class="accordion-body collapse" id="{{appname.replace(' ','')}}">
<p class="highlightable" >
Some data
</p>
</div>
</div>
The data in this ng-repeat comes from the server.
So the problem statement I have is to perform a click trigger on the first element under ng-repeat, .accordion-head so that the first item in the list is always open. I tried various approaches of putting $watch etc. but when the number of items in the list are same, then the trigger doesn't fire.
(the first item in list has to be clicked even when new data is loaded)
I thought of writing a directive initial-select and perform click based on index but that happens only once. I really need an experts advice.
Any solutions?
I think the simplest option is to use data-ng-init="collapse = !$first;".
Another option:
Have you used Angular UI Bootstrap? Also, are you using $http or $resource to get data from the server?
If you use $resource, you can set a variable on the success callback (interceptor response) to open=true. Then, you can either bind this variable to Angular UI Bootstrap is-open attribute or to your data-toggle. Also, with $resource you can set data-ng-if="chart.accordionData.$resolved" (or chart.$resolved depending on your setup), which is nice.
You can use a watch to watch the array contents.
Check out the following fiddle:
http://jsfiddle.net/akonchady/w0qdsen7/3/
I have used a variable to keep track when the array content changes since directly watching the array will be more memory intensive.
Here is the main code that watches the variable:
$scope.$watch('arrModified', function(newValue, oldValue) {
if(newValue) { //array is modified
//Trigger ng-repeat div click
setTimeout(function() {
$('.item:first').trigger('click');
$scope.arrModified = false;
$scope.$digest();
}, 0);
}
});
I am working on an app that submits the form and get the result from the server which followed by HTML table view. My input form is a bit big which covers whole the screen. When the table comes then I want automatically scroll down at the table view. I used $anchorScroll from angularJs. But I am not able to achieve the result what I want. I also used $timeout to make sure the table is already exist or not and then perform $anchorScroll, but still no success. (based on this solution : Using $location and $anchorScroll to scroll a table row into view
Hear is my code.
HTML
<div data-ng-controller="searchController as searchCtrl" id="scrollArea">
<form>
//HTML input elements
<div class="buttons">
<md-button class="md-primary md-raised" ng-click="searchCtrl.gotoTable('resultTable')">Start</md-button>
</div>
</form>
</div>
<!-- Smart Table for displaying result -->
<div class="rtable" ng-show = "searchCtrl.tableViewData.length > 0" id="resultTable">
//table content
</div>
Controller
angular.module('myApp')
.controller("searchController", function($log, searchService, $scope, $location, $anchorScroll, $timeout){
var self = this;
self.gotoTable = function(resultTable)
{
$timeout(function() {
$location.hash(resultTable);
$anchorScroll();
});
};
});
I dont know why its not working?
Do i need to define the id scrollArea and resultTable in my CSS?
Any help would be appreciated.
Thanks in advance.
UPDATE
Based on Okazari's solution, I tried to put a another div with many br tag above at the very bottom of my HTML. Now When I refresh the page then it automatically scroll to that div tag without clicking Start. this is a bit weird. I also tried to cover the
<div class="rtable" ng-show = "searchCtrl.tableViewData.length > 0" id="resultTable">
tag with another div tag with id = "resultTable".
But still it did not work.
You actually are invoking your function without any parameters
ng-click="searchCtrl.gotoTable()"
whereas in your controller you expect to have one :
self.gotoTable = function(resultTable)
Try something like this
ng-click="searchCtrl.gotoTable('resultTable')"
or this :
self.gotoTable = function()
{
$timeout(function() {
$location.hash("resultTable");
$anchorScroll();
});
};
(just one, not both)
Hope it helped.
EDIT : Pretty sure that you can't go to a hidden div. As i said in comment your ng-show may be evaluated to true when you try to anchorscroll().
Here is a working plunker without ng-show. I'll build a tiny solution to avoid the ng-show issue.
To avoid this side effect, i wrapped the div with ng-show with another div.
<div id="resultTable">
<div class="rtable" ng-show = "searchCtrl.tableViewData.length > 0">
</div>
All of the examples I have found show the radio button group being built by some for item in items loop but none of them show a simple accessing of the radio button group array in the angularjs controller. What I need to do is traverse through the button group array to see if any of them are in "selected" state.
var radioSelected = false;
for(var i =0; i < items.length; i++) {
if(items[i].selected) {
radioSelected = true;
}
}
I have tried binding to the ng-model and accessing it .. I have tried using $scope.ButtonGroupName Nothing yeilds an array that I can traverse with a loop. Any suggestions on how to do this once VERY simple activity would be greatly appreciated.
Gotta love being forced to relearn web development because somebody broke out a new shiney hammer.
You would not traverse the DOM elements. You would use the same ng-model for all the radio elements, and that would be updated whenever you change the selected state of the radio button.
<input type="radio" ng-model="assignedValue" name="myRadio" value="one">
<input type="radio" ng-model="assignedValue" name="myRadio" value="two">
<input type="radio" ng-model="assignedValue" name="myRadio" value="three">
You would $watch the $scope.assignedValue for changes instead of traversing the DOM elements.
$scope.$watch('assignedValue', function (newValue, oldValue) {
..do stuff here
});
See here for documentation: https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
The reason you don't traverse the DOM is because it's constantly changing. The whole point of Angular is to work off of data and not the elements themselves.
Update: Based on your comments, it sounds like only want to execute an action if a radio button has been selected.
First, a radio button should always have a selected state. Let's pretend it doesn't though. You can enable / disable / show / hide elements in angular in a couple of ways without writing additional DOM manipulation code.
Taking the example above, this button will only be enabled if the assignedValue is two.
<button ng-disabled="assignedValue != 'two'">My button</button>
You can also conditionally include content using ng-if:
<div ng-if="assignedValue == 'two'>
My conditional content
</div>
This will also work with ng-switch
<div ng-switch on="assignedValue">
<div ng-switch-when="two">My additional content</div>
<div ng-switch-default>Here's switch fallback content</div>
</div>
I am working on a website that displays numerous articles. Each article has a comment section. I have effectively been able to recursively write the comments to the DOM with recursion inside an ng-repeat. However, I need to be able to click on a respond button on any of the comments (they display in a nested fashion) and for a div to be inserted beneath the clicked button. This div would contain a text area for the comment they want to submit and a button. When this second button is clicked, the controller will save the comment to the database. I initially wanted to do this by directly manipulating the DOM from the controller. However, after further research, that would be in direct violation of the MVC/MVW pattern. I believe the correct answer is to create a custom directive. Please give me some insight on how to correctly do this. Any and all information would be very helpful. Thanks in advance.
If you want to add response div dinamically:
<div ng-repeat="article in articles" id="article-{{$index}}">
<p>{{article.content}}</p>
<button ng-click="addAnswer($index)">Add Answer</button>
</div>
js:
myApp.controller("articlesController", function($compile){
$scope.addAnswer = function (index) {
var div = $("<div></div>");
var input = $("<input type='text' ng-model='article.response'></input>");
div.append(input);
var button = $("<button>Send</button>");
button.attr("ng-click", "sendResponse(article)");
$compile(div)($scope);
$("#article-" + index).append(div);
};
});
You don't really need to make a directive to achieve this.
html:
<div ng-repeat="article in articles">
<p>{{article.content}}</p>
<input type="text" ng-model="article.response"></input>
<button ng-click="sendResponse(article)">Send</button>
</div>
js:
myApp.controller("articlesController", function($http){
$scope.sendResponse = function (article) {
console.log(article.response);
$http.post(url, article);
};
});
Of course, you can do it better by hidding input and send button, and show it after user clicks over an answer button.