AngularJS and MVC routing problems - javascript

I am having some problems with my routing.
My HomeController (ASP) Has few ActionViews Index - displays list of products,
Add, Edit, Delete.
Edit Action of course takes me to the EditView. So far so good.
Problem is that in this view angular kickes in (I am passing asp mvc model to angular in ng-init).
ng-controller="routeEditCtrl" data-ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))"
Then after edit controls I have Save and cancel button defined as follows:
<button class="btn btn-success" ng-click="validateAndSubmit()"><i class="fa fa-edit"></i> Save</button>
<i class="fa fa-trash"></i> Cancel
The cancel button works fine. However the angular controller methods does not work that nice.
$scope.validateAndSubmit = function () {
//var result = $scope.ctrlCode.validate();
if (true) {
$http.post("SaveRoute", $scope.model).success(function (data) {
$scope.model = data;
$location.path("Index");
}).error(function (data) {
});
}
}
}]);
On successful post I wanted go back to Index view.
How can I archive that?

Related

ng-click on button that is ng-included

I have a problem. I'm trying to include a button that's on a html template page on to my index.html page. I do it like this
<ng-include src="'logout/logout.template.html'"></ng-include>
The page is:
<button type="button" class="btn btn-default btn-sm" ng-click="$ctrl.lala()">
<span class="glyphicon glyphicon-log-out" ></span> Log out
</button>
The problem is, the thing doesn't work. It won't access the ctrl function. As I read, ng-include doesn't work well with other angular directives so my question is, how else can I include my button template in the index.html without copy pasting the code because it's connected to a componenet an dservice so I can't break it.
The componenent:
'use strict';
angular
.module('logout')
.component('logout', {
templateUrl: 'logout/logout.template.html',
controller: ['$scope', '$location', '$localStorage', 'Logout',
function LogoutController($scope, $location, $localStorage, Logout) {
this.lala = function () {
console.log("doing logout");
}
}
]
});
I know it sounds like an overkill, but I would just create another component for it. If lala() is the function that actually logs the user out then it's best to include that in the component too, so you don't have to repeat it in every parent component.
Take a look at this jsfiddle for a complete sample. I wrote everything in the html, but I copied the important part below:
https://jsfiddle.net/6cjd5ggq/1/
<logout></logout>
angular.module('logoutapp')
.controller('logoutController', logoutController)
.component('logout', {
// you can use templateUrl, but it's easier this way in jsfiddle
template: `<button type="button" class="btn btn-default btn-sm" ng-click="$ctrl.lala()">
<span class="glyphicon glyphicon-log-out"></span> Log out
</button>`,
controller: 'logoutController'
});
function logoutController() {
this.lala = function() {
alert("logout!");
};
}

How do I get $emit to controller from directive built html

I'm having difficulty figuring this out. I have a directive building html from promise data. For each row, it's adding buttons for CRUD operations. I do not know how to get the button event to trigger in my controller. Regardless of how my controller is set up, how can I get the event to register in my controller? I am currently trying $emit, but nothing seems to happen.
Directive generated html:
controls = controls+'<button type="button" data-tooltip-placement="bottom" data-tooltip="'+action.name+'" ng-click="$emit(&apos;'+action.broadcaster+'&apos;,'+rowId+')" name="'+action.name+'" class="btn btn-xs btn-default ng-scope"><i class="'+action.icon+'"></i> </button>'
How it looks in Chrome tools:
<button type="button" data-tooltip-placement="bottom" data-tooltip="delete" ng-click="$emit('removeOrgCourse',134)" name="delete" class="btn btn-xs btn-default ng-scope"><i class="fa fa-trash-o"></i> </button>
and my controller listener:
$scope.$on('removeOrgCourse', function( event, data ){
console.log(data);
});
UPDATE:
Just changed the ng-click to console.log("click") and nothing happened. So the issue is that ng-click is not registering;
While you can use events in angular to achive that, one other option is to use & expression scope binding to pass controller method to directive. Example code (from egghead.io)(see working code at jsbin):
<div ng-app="phoneApp">
<!-- we've replaced the use of $scope with the preferred "controller as" syntax. see:http://toddmotto.com/digging-into-angulars-controller-as-syntax/ -->
<div ng-controller="AppCtrl as appctrl">
<div phone dial="appctrl.callHome(message)"></div>
<div phone dial="appctrl.callHome(message)"></div>
<div phone dial="appctrl.callHome(message)"></div>
</div>
Controller:
app.controller("AppCtrl", function() {
var appctrl = this;
appctrl.callHome = function(message) {
alert(message);
};
});
And directive:
app.directive("phone", function() {
return {
scope: {
dial: "&"
},
template: '<input type="text" ng-model="value">' +
'<div class="button" ng-click="dial({message:value})">Call home!</div>'
};
});
Maybe you have to use $broadcast, depends if the controllers are on the same level or who's over who.
Working with $scope.$emit and $scope.$on
http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
in the secon link you can put the $emit and $broadcast in the same controller and see whad do you catch in you $on

Add Friend with Ajax - Django

I'm using Django-Friends
I'm trying to have it so when a user clicks on the add friend, the button disappears(or ideally says Request sent). However, when I click the button, it doesn't disappears. I am new at Django and Ajax, so I'm assuming that this is an error on my part. Most likely the HttpResponse.
That part actually confuses me a lot. The HttpResponse, render, render_to_response, etc. I know that I can use render or render_to_response when I want to load a template. But what if I don't want to load up a new template or go to a new page? Like I want to be able to complete an action like add a friend, or add a page, etc; all on one page. I know you can use ajax to do it, but I don't know the django technical aspect of it.
Anyway, here's my code. Right now, nothing happens. The button doesn't disappear, and there is no friendships request sent.
profile.html
<div class="text-center">
<div>
"{{currUserprofile.tagline}}"
</div>
{{currUser.profile.city}}, {{currUser.profile.state}}
{{currUser.id}}
</div>
<!-- <button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
--> <!--Find a way to signify looking or not looking to mentor -->
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
ajax.js
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
})
views.py
#login_required
def profile(request, id):
context = RequestContext(request)
currUser = User.objects.get(pk = id)
profile = UserProfile.objects.filter(user = currUser)
return render_to_response('myapp/profile.html', {'currUser': currUser, 'UserProfile': UserProfile}, context)
#login_required
def addfriend(request, id):
context = RequestContext(request)
other_user = User.objects.get(pk=id)
new_relationship = Friend.objects.add_friend(request.user, other_user)
profile = UserProfile.objects.filter(user = other_user)
return HttpResponse(new_relationship)
Here is a working JSFiddle, but you can't post data {profile_id: profile_id}with a getyou should use a postor add the data as params, as I did:
HTML:
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
JS:
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/?profile_id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
});

Save items from controller into array on Yes / No basis

Having some trouble with angularJS i've only been working with it for two weeks and my javascript knowledge aswell is rather no existent so please take this into account.
Im currently making a hearing test app which all functionality is working apart from a reporting system im building into it.
Im wanting on a yes / no basis record at what frequency and DB they heard the sound from these two buttons.
<button ng-click='' type="button" class="btn btn-primary btn-lg glyphicon glyphicon-ok"></button>
<button ng-click='' type="button" class="btn btn-default btn-lg glyphicon glyphicon-remove"></button>
Here is an example of one of my controllers for 125HZ at 0DB as an example.
// 125 FREQUENCY START
myApp.controller('125Zero', ['$scope','ngAudio', function($scope, ngAudio) {
$scope.title = "Frequency: 125Hz";
$scope.frequency = "0Db";
$scope.sound = ngAudio.load("audio/125_0.mp3"); // returns NgAudioObject
$scope.previous =""
$scope.next ="125Ten"
}]);
Im wishing to record the $scope.title and $scope.frequency attribute into and array for later processing.
this is as far as ive got with the idea
function result() {
$scope.results = [];
$scope.resultService = function(){
$scope.results.push();
}
}
with no results, i want to save both title and frequency into the array, and allow the program to move onto the next controller and do the same if the frequency is heard.
Thanks for any help or ideas.
Apologies if my code isn't the cleanest or ideal but as i explained this is my second week working with AngularJS
Thanks.
Add event listeners to the buttons:
<button ng-click='buttonPressed('okay")' type="button" class="btn btn-primary btn-lg glyphicon glyphicon-ok"></button>
<button ng-click='buttonPressed("remove")' type="button" class="btn btn-default btn-lg glyphicon glyphicon-remove"></button>
In your controller, add those methods:
myApp.controller('125Zero', ['$scope','ngAudio', function($scope, ngAudio) {
$scope.title = "Frequency: 125Hz";
$scope.frequency = "0Db";
$scope.sound = ngAudio.load("audio/125_0.mp3"); // returns NgAudioObject
$scope.previous ="";
$scope.next ="125Ten";
$scope.buttonPressed= function(outcome) {
$scope.result = [];
var tempObj = {};
tempObj.title = $scope.title;
tempObj.frequency = $scope.frequency;
// check for outcome to find out if it's okay or remove.
//based on that set the frequency here.
$scope.result.push(tempObj);
// add this to service
}
}]);
To get this value in next controller:
You need to store that $scope.result inside a service. So create a service and push the $scope.result into that.
In your second controller, inject that service as a dependency and access the value there.

twitter bootstrap modal -- how to pass data to callback function

is there a way to pass additional data to bootstrap modal function callback?
for example, lets say my link that causes the modal to open has an extra attribute in it with a bit of useful data in it, how could I reference that attr?
HTML
<span listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
JS
$('#editTaskList').on('show', function () {
// get the source of the click, and then get the data i need.
});
Could this work for you ?
<span listid="80" href="#editTaskList" data-toggle="datamodal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
var $editTaskList = $('#editTaskList');
$('body').on('click.modal.data-api', '[data-toggle="datamodal"]', function (e) {
var $this = $(this);
$editTaskList.data('anyAttr',$this.data('anyAttr'));
$editTaskList.modal('show');
e.preventDefault();
})
$editTaskList.on('show', function () {
var myData = $editTaskList.data('anyAttr');
});
I know that this is an old question, but this is the first thing i've found on google. So, I want to put some important information here...
You NEED to put your callback function binded on events BEFORE you call the modal, for example:
$('#modal').on('shown', function(){
// Do something when the modal is loaded
});
$("#modal").modal();
This is very important and helped me a lot, so, here it is...
Like this -
<span id="modal_opener" data-extrastuff="stuff" listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
$('#modal_opener').click(function() {
var stuff_i_want = $(this).attr('data-extrastuff');
});

Categories

Resources