i want to get the text of div using angularjs . I have this code
<div ng-click="update()" id="myform.value">Here </div>
where as my controller is something like this
var myapp= angular.module("myapp",[]);
myapp.controller("HelloController",function($scope,$http){
$scope.myform ={};
function update()
{
// If i have a textbox i can get its value from below alert
alert($scope.myform.value);
}
});
Can anyone also recommand me any good link for angularjs . I dont find angularjs reference as a learning source .
You should send the click event in the function, your html code should be :
<div ng-click="update($event)" id="myform.value">Here </div>
And your update function should have the event parameter which you'll get the div element from and then get the text from the element like this :
function update(event)
{
alert(event.target.innerHTML);
}
i just thought i put together a proper answer for everybody looking into this question later.
Whenever you do have the desire to change dom elements in angular you need to make a step back and think once more what exactly you want to achieve. Chances are you are doing something wring (unless you are in a link function there you should handle exactly that).
So where is the value comming, it should not come from the dom itself, it should be within your controller and brought into the dom with a ng-bind or {{ }} expression like:
<div>{{ likeText }}</div>
In the controller now you can change the text as needed by doing:
$scope.likeText = 'Like';
$scope.update = function() {
$scope.likeText = 'dislike';
}
For angular tutorials there is a good resource here -> http://angular.codeschool.com/
Redefine your function as
$scope.update = function() {
alert($scope.myform.value);
}
A better way to do it would be to use ng-model
https://docs.angularjs.org/api/ng/directive/ngModel
Check the example, these docs can be a bit wordy
Related
how can I create in an AngularJS directive some DOM elements and set on them a click event? In my directive I create my elements in this way:
var list = document.createElement("div");
list.classList.add('myList');
for(var i = 0; i < n; i++) {
var item = document.createElement("div");
item.classList.add('myItem');
list.appendChild(item);
}
so I have an external div container that contains some div elements.
This is my generated HTML:
<div class="myList">
<div class="myItem">
<div class="myItem"></div>
<div class="myItem"></div>
<div class="myItem">
</div>
In the same directive I have to set a click event on those elements, in jQuery I can do:
$(".myItem" ).on( "click", function() {
// Do something
});
I try to that in Angular in many ways but I have problems to set the on click event:
var list = document.querySelector('.myList');
_.forEach(list.children, function(value, index){
var item = document.querySelector(value);
item.bind("click",function(){
// Do something
});
});
I get an error:
Failed to execute 'querySelector' on 'Document': '[object HTMLDivElement]' is not a valid selector.
Also, if I want get all myItem directly (without list.children) I write use:
var item = document.querySelector('.myItem');
I get:
item.bind is not a function (caused by "undefined")
I can set an ng-click in the directive... how?
item.on( "click", function() {
// Do something
});
If I use .on() method it's undefined like .bind().
Anyone can help me? Thanks in advice :)
I believe what you need is
<div class="myList">
<div class="myItem" ng-click="yourClickFn()">
<div class="myItem" ng-click="yourClickFn()"></div>
<div class="myItem" ng-click="yourClickFn()"></div>
<div class="myItem" ng-click="yourClickFn()">
Then in your Angular controller:
$scope.yourClickFn = function(){
//the code you want to execute here
}
Do you have a real reason to create your elements this way? It's really not the angular-way of doing things. You should use an ng-repeat on to create your html.
Also if you have a chance to update to anguar 1.5+ you could use components instead of directives, this would make your life easier.
Update
Alternatively you could do it with jQuery after the elements are created actually. I think it's easier to read than the plain js version.
Put a class on them and do something like:
$('.myClass').on('click', function() {
//your code
if (!$scope.$$phase) { // this checks whether you are already in a digest cycle or not - you probably won't be at this phase.
$scope.$apply(); // this will update the html if you did something to the model above this if
}
});
If you have a directive put this code to the link function, if you have a component then put it into the $postLink lifecycle hook (works after 1.5.3 I think) as these functions are called after your html has been already generated.
Usually these are the places for "messy" or "non-angular" code ^_^
Im new to knockoutJS and really loving it. I'm trying to build something very similar to this http://jsfiddle.net/mac2000/N2zNk/light/. I tried copying the code and adapting it to my need. The problem with that is that I get my data from the server using $.getJSON it seems that the jsfiddle example was made for a different format of data which just confuses me.
So instead of asking for help to find the issue with my code I rather take a different approach. Hopefully you guys wont mind. Im starting from scratch and trying to learn each steps so I know what im doing.
Here is my code so far, this works great to simply display my data on my table.
<script type="text/javascript">
function EmployeeModal() {
var self = this;
self.Employees = ko.observableArray([]);
$.getJSON("../../../../_vti_bin/listData.svc/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc",
function (data) {
if (data.d.results) {
self.Employees(ko.toJS(data.d.results));
}
}
);
}
$(document).ready(function () {
ko.applyBindings(new EmployeeModal());
});
</script>
I made a template where each row has an edit button similar to the example but no fucntion of binding are done yet. Now what I would like to do is simply onlick pass the selected data to my modal and show my modal like so:
$('#myModal').modal('show');
This is the step im struggling the most with. Would any have any clear documentations for a noob or example, hints or any type of help I would take to get me in the right direction from here.
Assume you have them in a list like this:
<ul data-bind="foreach: Employees">
<li data-bind="text: fullName, click: showEmployee"/>
</ul>
What I'd recommend is to update your view model to look like this:
function EmployeeModal() {
var self = this;
self.Employees = ko.observableArray([]);
self.currentEmployee = ko.observable(null);
self.showEmployee = function(vm){
self.currentEmployee(vm);
$('#myModal').modal('show');
};
.... // rest of your view model here
}
The last piece will be using KO's with binding to wrap your modal
<div class="modal" id="myModal" data-bind="with: currentEmployee">
<h1 data-bind="text: fullName"></h1>
</div>
What this does is listen for the click event on an individual element and automatically pass the view model bound to that element to the click handler you defined. We're then taking that view model, storing it in its own observable and then showing the modal like normal. The key here is the with binding which only executes when there's data stored in the observable, and also sets the context of all nested code to be the employee stored in currentEmployee.
There's a lot there if you're new, but using a current style observable to track individual data from a list is a great paradigm to use with Knockout = )
P.S.. the http://learn.knockoutjs.com/ tutorials are really great to work through if you've yet to do so.
I've built a page with 3 elements, each of which looks like this:
<div class="col-md-4 event-type">
<a href="{{ pathFor 'step2' }}" id="eventchoice" name="eventchoice" value="corporate">
</a>
</div>
I'm trying to pass the value or name or id of the the <a> element on to a collection using the following code:
EventsController.events({
'click #eventchoice' : function(event) {
console.log(event.target.getAttribute("id"));
console.log(event.target.getAttribute("name"));
console.log(event.target.getAttribute("value"));
var eventchoice = event.target.value;
var params = {
eventchoice: eventchoice
}
//Insert Event
Meteor.call('addEvent', params);
FlashMessages.sendSuccess('Event Added');
}
});
I added the console.log's to see if I can get the id/name/value of the <a> element, but the console outputs 'null' for all of these. Therefore, there is nothing to pass to the collection in the eventAdd method.
I don't believe the problem is with the EventsController, the addEvent method or the Events collection. Any ideas how I can pass these values through?
Thank you for your help!
I think there must be something wrong with your controller then, because if you check the Meteorpad here, it works just fine.
Although you might want to use a class instead of an id if you have many similar elements.
There are several ways of solving your problem but the way I consider as "The Meteor Way" is to use a separate template for every choice (or just use #each loop), if you do that your "this" inside the event code will contain the values you need in your scope, so you won't have to rely on the event.target for them.
I have a simple boolean variable that switches a DIV to be hidden at startup and then shown after an action until the end of the application. But it does not switch - the DIV is always hidden. Please help, what is wrong in the code below:
<div class="right" ng-controller="EmployeeDetailsCtrl" ng-show={{showEmployeeDetails}}>
<p>{{employee.name}} {{employee.surname}}</p>
</div>
inside EmployeeDetailsCtrl controller:
$scope.$on('showEmployee', function (event, data) {
$scope.showEmployeeDetails = true;
$scope.employee = data;
});
$scope.showEmployeeDetails = false;
BTW, the $scope.employee variable updates correctly after the event is triggered, so I'm really stuck what's going on here.
Remove the {{}} from your ng-show, like so:
<div class="right" ng-controller="EmployeeDetailsCtrl" ng-show="showEmployeeDetails">
<p>{{employee.name}} {{employee.surname}}</p>
</div>
When you're using ng-show you're binding to an expression, not a string, so just use:
ng-show="showEmployeeDetails". That's why you can do more complex stuff like ng-show="1 + 1 === 2".
If that still doesn't cut it, it could be a scoping issue with primitives being assigned to a child scope and not seen up the parent scope. It doesn't look like it from the code you showed but perhaps it's simplified for this question, you never know.
Okay, I'm very new to angular and I read already about it from different sources to understand it well enough,
apparently I'm still struggling to make it work in some way,
I already had the simple htmlpage:
<html>
<body ng-app>
<div id="content"></div>
</body>
</html>
then, after I request the data to the server, I create something like this:
function updateView($scope){
$scope.test="Success";
}
window.onload=function(){
var content = document.getElementById("content");
var add = document.createElement("div");
add.innerHTML = "{{test}}";
content.appendChild(add);
content.setAttribute("ng-controller", "updateView");
};
and what I got as a result was an html page with a text : {{test}}
so I assume that it's not working,
I know that this might have something to do with creating the content and ng-controller on the fly, and this can be accomplished in more basic way as many tutorial does, but I need the method I specified (add attribute and content(test) on the fly) because I will display something I request from the server which can have varied amount of data, say if it has 3 data in an array form, the "var add=document.createElement("div")" will be called 3 times and I will need to attach the attribute ng-controller to each of them
Is there a work around that I haven't known yet?
In order to accomplish what you are trying to do in Angular you will need to use the $compile service, which you can read more about here. This allows you to append html to the dom and link it to your scope variables.
For your specific example you could get the $compile service in the window.onload method like this:
window.onload=function(){
angular.element("body").injector().invoke(function ($compile) {
var content = document.getElementById("content");
var add = document.createElement("div");
add.innerHTML = "{{test}}";
content.appendChild(add);
content.setAttribute("ng-controller", "updateView");
$compile(template.contents())(scope);
});
};