Generate and track same template multiple times using Knockout in MVC view? - javascript

I put together a Contacts prototype MVC application that uses Knockoutjs. I'm fairly new to Knockout and was wondering if my design is correct in reaching my end goal. My end goal is basically to take an MVC Model that is passed to my Contacts view to start and achieve the following:
Mapping it to my KO Viewmodel.
Use Bootstrap Modal Popup to input my contact data.
Upon Clicking Add in Bootstrap Modal call template after posting JSON
data to controller successfully and have it display under
Edit button on each template rendered under div if clicked brings up same Modal Popup to edit that templates data.
Here's the code breakdown of what I have currently in place.
View Code
<h2>Contacts List</h2>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10"><h3>KO Results</h3></div>
</div>
<br />
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10"><div id="koResults" data-bind="template: { name: 'contactSectionTmp', foreach:Contacts }"></div></div>
</div>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10"><strong>Add</strong></div>
</div>
#*I enter data in my bootstrap modal shown below and when I click "Add" the Template below appears
in div element koResults with the data I just entered. This is the desired effect I'm looking for. *#
<div class="modal" id="contactModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" style="background-color:#B8E28D; border-color: black">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Contact</h4>
</div>
<div class="form-horizontal">
<form id="contactModalForm" data-bind="with:newContact,submit:add">
<div class="modal-body">
<h4>Contact</h4>
<div class="form-group">
<label class="col-sm-4 control-label">Name:</label>
<div class="col-sm-8">
<input type="text" name="Name" class="form-control" data-bind="value: Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Address:</label>
<div class="col-sm-8">
<textarea rows="4" cols="50" name="Address" class="form-control" data-bind="value: Address"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Phone:</label>
<div class="col-sm-8">
<input type="text" name="Phone" class="form-control" data-bind="value: Phone" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="formSubmitContact" class="btn btn-success">Add</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
#section scripts
<script type="text/javascript" src="~/Scripts/knockout-3.4.0.debug.js"></script>
<script type="text/javascript" src="~/Scripts/knockout.mapping-latest.debug.js"></script>
#* Knockout Template *#
<script id="contactSectionTmp" type="text/html">
<div class="row">
<div class="col-lg-3">Name:</div>
<div class="col-lg-9" data-bind="text: name"></div>
</div>
<div class="row">
<div class="col-lg-3">Address:</div>
<div class="col-lg-9" data-bind="text: address"></div>
</div>
<div class="row">
<div class="col-lg-3">Phone:</div>
<div class="col-lg-9" data-bind="text: phone"></div>
</div>
</script>
End Section
Controller Code
Pass in model to view here.
public ActionResult ContactsList()
{
ContactsVM mData = new ContactsVM();
mData.Contacts = new List<Contact>(){ new Contact { ID = 1, Name="Drew Lucacca", Address="782 Select St.", Phone="421-821-9101"},
new Contact {ID = 2, Name="Kevin Rosassa", Address = "222 Potter Lane", Phone="421-982-5222" },
new Contact {ID = 3, Name="Tim Kropp", Address = "440 PPG Place", Phone="725-434-8989"} };
return View(mData);
}
[HttpPost]
public ActionResult ContactCreate(Contact newContact)
{
var res = newContact;
ContactsVM myContacts = new ContactsVM();
myContacts.Contacts = new List<Contact>();
myContacts.Contacts.Add(new Contact { ID = 4, Name = "Santa Claus", Address = "440 Trump Plaza", Phone = "774-489-8989" });
return Json(myContacts);
}
Javascript Code
` //Main ViewModel
function ContactsVM(data) {
var self = this;
var mapping = {
'Contacts': {
create: function(options) {
return new Contact(options.data);
}
}
};
ko.mapping.fromJS(data, mapping, self);
self.newContact = ko.observable();
self.addContact = function() {
debugger;
self.newContact(new Contact({Name: '', Address: '', Phone: ''}));
}
self.add = function () {
debugger;
var jsData = data;
var jsData1 = ko.mapping.toJSON(self.newContact());
$.ajax({
url: '#Url.Action("ContactCreate", "Home")',
type: 'POST',
data: ko.mapping.toJSON(self.newContact()),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (jsonObject) {
self.contacts.push(new Contact(jsonObject));
}
});
// Close the modal.
$('#contactModal').modal('toggle');
};
self.cancel = function () {
// Close the modal.
$('#contactModal').modal('toggle');
};
//self.resetForm = function (formId) {
// var form = $('#' + formId);
// form.validate().resetForm();
// form.get(0).reset();
//};
};
function Contact(data) {
ko.mapping.fromJS(data, {}, this);
this.isEdit = ko.observable(false);
};
$(function () {
var jsonModel = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model));
var vm = new ContactsVM(jsonModel);
ko.applyBindings(vm);
});
Contact Entity
public class Contact
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
ContactsVM Entity
public class ContactsVM
{
public List<Contact> Contacts { get; set; }
}
EDIT #1
See here's the thing I know that the javascript isn't correct and note that in javascript comments asking if you can help me identify if it isn't correct how should it be.
I moved the code to new location at bottom of MVC view for the Javascript code didn't seem to find model.
Javascript - Knockout - Mapping Error
JavaScript runtime error: 'push' is undefined
self.contacts.push(new Contact(jsonObject)); < --- Error happens here.
Any help here would be greatly appreciated and I'm sure would help others as well.

I think it might be best for you to take an iterative approach at getting this working, based on the steps you have listed. Do one thing at a time, get it working, then move on to the next item. Trying to work out everything at once and test it altogether is really tough.
First Recommendation: Make your client-side models reflect your server-side models. After that, things just get easier. Since you are using ko mapping, your client-side model setup gets easier:
function ContactsVM(data) {
var mapping = {
'Contacts': {
create: function(options) {
return new Contact(options.data);
}
}
};
ko.mapping.fromJS(data, mapping, this);
this.newContact = ko.observable();
}
function Contact(data) {
ko.mapping.fromJS(data, {}, this);
this.isEdit = ko.observable(false);
}
Then you can create and apply the top-level view model fairly easily as well:
var vm = new ContactsVM(jsonModel);
ko.applyBindings(vm);
This gives you a top-level viewmodel with a fully filled Contacts observable array property. You can use the newContact property for your modal to add a new contact, just fill it with a new Contact instance.
new Contact({Name:'', Address:'', Phone:''})
When you push this new contact to the array of contacts, the DOM will automatically update to display the new contact, so you won't need to use the "ko.renderTemplate" logic that you specified. I imagine you could also show/hide the modal based on if this observable has a value if you wanted to.
Second recommendation: Try doing things with knockout first, and if you can't then use jQuery. I would not recommend using jQuery to serialize form values. Remember, you have direct access to client-side models, so you are no longer dependent upon the DOM. The ko mapping plugin has a method to unmap back to a regular JS object.

Related

How to print data from database onto model popup box?

I have books retrieved from database in the Index view. Each one has a button below. When you click them a modal box should pop up with the corresponding book details (book img, name title, decsription, price etc) printed on it.
Index View:
<!-- language: lang-html -->
#model AuthorTest.Models.HomeModel
<!--razor codes where book properties are called-->
#foreach(var book in Model.Bestsales)
{
<a class="first__img" href="single-product.html"><img src="~/Uploads/img/#(book.Id + " .jpg ")"</a>
<h4>product.html">#book.Name</a></h4>
<ul class="prize d-flex">
<li>#book.Price</li>
</ul>
<!--modal-box pop-up button-->
<a data-toggle="modal" title="Quick View" data-id="#book.Id" class="modal-open" href="#productmodal"><i class="bi bi-search"></i></a>
}
I'm trying to pass a book id using ajax
<!-- language: lang-js-->
#section scripts{
<script>
$(".modal-open").click(function () {
var id = $(this).data("id");
$.ajax({
type: "POST",
url: "/Home/Details/" + id
});
});
</script>
}
into the "Details" action that retrieves related book and returns it to a view where modal box content is placed.
<!-- language: lang-cs-->
[HttpPost]
public ActionResult Details(int id)
{
HomeModel model = new HomeModel();
var book = db.Books.Where(b => b.Id == id).Include(b => b.Author).SingleOrDefault();
if (book == null)
{
HttpNotFound();
}
book.DisplayNumber++;
db.SaveChanges();
model.bookDetails = book;
return view( model);
}
This is the HomeModel class that I use to keep two models 1)list property of type Book to loop through my books in the Index view
2)property of Book type to call model-related book datas in "Details" view:
<!-- language: lang-cs-->
public class HomeModel
{
public List<Book> BestSales { get; set; }
public Book bookDetails { get; set; }
}
a view where modal box content is placed:
<-- language: lang-html-->
#model AuthorTest.Models.HomeModel
div id="quickview-wrapper">
<!-- Modal -->
<div class="modal fade" id="productmodal" tabindex="-1" role="dialog">
<div class="modal-dialog modal__container" role="document">
<div class="modal-content">
<div class="modal-header modal__header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="modal-product">
<!-- Start product images -->
<div class="product-images">
<div class="main-image images">
<img alt="big images" src="~/Uploads/img/#(Model.bookDetails.Id + ".jpg")">
</div>
</div>
<!-- end product images -->
<div class="product-info">
<h1>#Model.bookDetails.Name</h1>
<div class="rating__and__review">
</div>
<div class="price-box-3">
<div class="s-price-box">
<span class="new-price">#Model.bookDetails.Price</span>
<span class="old-price">$34.00</span>
</div>
</div>
<div class="quick-desc">
#Model.bookDetails.Description
</div>
<div class="addtocart-btn">
Add to cart
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
When I click modal-open button the id gets passed to the "Details" action, corresponding book is retrieved and takes me to the view. But it seems like modal box pops up before ajax runs action and therefore the data is not printed. Where do I make mistake? How to pass the book details into the modal-box correctly?
An Ajax call is asynchronous, so you must get in this mindset: when you work in a non sync way, you shall manage async calls with callbacks. jQuery offers different types of callback for the $.ajax() method, such as "success","error".... on and on. If the ajax call results in a server exception for instance, the HTTP result will be 500 and you can manage it in the "error" callback subscribing the callback with a your custom method that will be raised by jQuery. On the other way, the success callback must be subscribed by a method that accepts parameters where will be the server response (in this case, an html response). So, if the result is a success (HTTP Status code 200), you will have the HTML in that parameter, and you can use it to append in your modal (always with jQuery methods... or even in simple javascript if you like more)
Take a look to callbacks subscriptions:http://api.jquery.com/jquery.ajax/ in the "Callback Function Queues" section. You will find out that I gave you just a real basic explanation and there's a lot of more to learn!

POST request doesn't recognize in my controller using Opencart

I have a problem in my code. In my setup I created a single page for language selection. And I copy some of opencart's code on language template and also on controller. But my problem is after passing my form, the action controller doesn't get any POST data from my form.
<form action="{{ action }}" method="POST" enctype="multipart/form-data" id="form-language">
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>ENGLISH</h3>
<button class="language-select btn btn-green" type="button" name="en-gb">Choose</button>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>日本語</h3>
<button class="language-select btn btn-green" type="button" name="jap">選択</button>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>中文</h3>
<button class="language-select btn btn-green" type="button" name="zh-hk">选择</button>
</div>
</div>
</div>
</form>
JS:
// Language
$('#form-language .language-select').on('click', function(e) {
e.preventDefault();
$('#form-language input[name=\'code\']').val($(this).attr('name'));
$('#form-language').submit();
});
Controller to show my language selection page
public function language_switch() {
$this->load->model('setting/extension');
$this->document->setTitle($this->config->get('config_meta_title'));
$this->document->setDescription($this->config->get('config_meta_description'));
$this->document->setKeywords($this->config->get('config_meta_keyword'));
if (isset($this->request->get['route'])) {
$this->document->addLink($this->config->get('config_url'), 'canonical');
}
$data['action'] = $this->url->link('common/language/language');
$data['code'] = $this->session->data['language'];
$styles_array = array(
'catalog/view/theme/onemidorie/stylesheet/style.css'
);
$scripts_array = array(
);
foreach($styles_array as $st) {
$this->document->addStyle($st);
}
foreach($scripts_array as $sc) {
$this->document->addScript($sc);
}
$data['styles'] = $this->document->getStyles();
$data['scripts'] = $this->document->getScripts();
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
$this->response->setOutput($this->load->view('common/language_selection', $data));
}
Controller that should accept the POST data from my form:
public function language() {
print_r($this->request->post['code']); //Notice: Undefined index: code
die;
if (isset($this->request->post['code'])) {
$this->session->data['language'] = $this->request->post['code'];
}
if (isset($this->request->post['redirect'])) {
$this->response->redirect($this->request->post['redirect']);
} else {
$this->response->redirect($this->url->link('common/home'));
}
}
Can you help me this?
You should use
print_r($this->request->post);
die;
Then you will get some post data.
because you define the name like "en-gb","jap" and "zh-hk". So please use above code then you can get solution.
You're not posting any data - you're just showing a button. Use something more like
<input type="submit" value="english" name="lang"/>
<input type="submit" value="japanese" name="lang"/>
etc. then just look at
$_POST['lang']
and see if it's english, japanese or whatever.
You can find out how opencart set language in /catalog/controller/startup/startup.php:
// Overwrite the default language object
$language = new Language($code);
$language->load($code);
$this->registry->set('language', $language);
So in controller what should accept the POST data you should dublicate this code before loading language:
// $this->request->post['code'] = 'en-gb' or 'ru-ru' or whatever.
$language = new Language($this->request->post['code']);
$language->load($this->request->post['code']);
$this->registry->set('language', $language);
// now opencart use new language and you can use it too:
$this->load->language('common/header');
$text_home = $this->language->get('text_home');
This works for me in opencart 2

Form modal binding in laravel with vue js

I have 2 models Tour.php
public function Itinerary()
{
return $this->hasMany('App\Itinerary', 'tour_id');
}
and Itinerary.php
public function tour()
{
return $this->belongsTo('App\Tour', 'tour_id');
}
tours table:
id|title|content
itineraries table:
id|tour_id|day|itinerary
In tour-edit.blade.php view I have used vue js to create or add and remove input field for day and plan dynamically.
Code in tour-create.blade.php
<div class="row input-margin" id="repeat">
<div class="col-md-12">
<div class="row" v-for="row in rows">
<div class="row">
<div class="col-md-2">
<label >Day:</label>
<input type="text" name="day[]"
class="form-control">
</div>
<div class="col-md-8">
{{ Form::label('itinerary', " Tour itinerary:", ['class' => 'form-label-margin'])}}
{{ Form::textarea('itinerary[]',null, ['class' => 'form-control','id' => 'itinerary']) }}
</div>
<div class="col-md-2">
<button class="btn btn-danger" #click.prevent="deleteOption(row)">
<i class="fa fa-trash"></i></button>
</div>
</div>
</div>
<div class="row">
<button class="btn btn-primary add" #click.prevent="addNewOption" >
<i class="fa fa-plus"></i> Add Field</button>
</div>
</div>
</div>
I want to populate these fields with their respective data. But all data i.e itinerary belonging to a tour are being displayed in itinerary textbox in JSON format.
My vue js sript is:
<script>
var App = new Vue({
el: '#repeat',
data: {
day:1 ,
rows:[
#foreach ($tour->itinerary as $element)
{day: '{{$element->day}}', plan: '{{$element->plan}}'},
#endforeach
]
},
methods: {
addNewOption: function() {
var self = this;
self.rows.push({"day": "","itinerary":""});
},
deleteOption: function(row) {
var self = this;
self.rows.splice(row,1);
},
}
});
</script>
I would avoid mixing blade into JavaScript, instead the best option is to make an ajax call to an api route which returns your data in json, which can then be processed by Vue:
methods:{
getItinerary(){
axios.get('api/itinerary').then(response => {
this.itinerary = response.data;
})
}
}
However, with this approach you will likely need to use vue-router rather than laravel web routes, which puts us into SPA territory.
If that's not an option (i.e. you still want to use blade templates), you should take a look at this answer I gave the other day which shows you how to init data from your blade templates.
What you seem to be doing is using laravel's form model binding to populate your forms, not Vue, so your model data is not bound to the view. So, you will need to decide which one you want to use. If it's vue you just want to use a normal form and bind the underlying data to it using v-model:
Now any updates in the view will automatically be updated by Vue. I've put together a JSFiddle that assumes you will want to continue using Laravel web routes and blade templates to show you one approach to this problem: https://jsfiddle.net/w6qhLtnh/

Bootstrap Modal in MVC 5 Razor: How do I update model boolean value to false when user clicks continue button in modal?

I want to try to implement this with Ajax post request, but I've never used Ajax and I'm not sure how to go about doing this.
My view code for password panel look's like this:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Reset Password</h3>
</div>
<div class="panel-body" id="myForm">
#using (Html.BeginForm("EditPassword", "Users", new { UserId = Model.User.Id, Token = Model.Token }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control", #type = "text" })
</div>
</div>
<div id="dialog-modal" style="display:none;" title="Basic modal dialog"></div>
<div class="col-md-9">
<button type="submit" data-toggle="modal" data-target=".bootstrapmodal" class="btn btn-primary" value="Reset" onclick="javascript: return checkPassForm(document.getElementById('myForm'));">Reset</button>
</div>
}
</div>
Bootstrap Modal code:
<div class="modal fade bootstrapmodal" id="modalMain" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false" data-keyboard="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button data-dissmiss="modal" class="close modal-close-btn" data-dismiss="modal" aria-hidden="true"> <span>×</span> </button>
<div class="modal-title"><h3>News Letter Account</h3></div>
</div>
<div class="modal-body">
<p>This is a newsletter only account which does not have an existing password.</p>
<p>Do you wish to create a mySewnet account for this user?</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="btn-updateNL"> Continue </button>
<button class="btn btn-default cancel-modal" data-dismiss="modal" aria-hidden="true"> Cancel</button>
</div>
</div>
</div>
</div>
Script code in the same view looks as follows
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
$("#btn-updateNL").on('click', function (e) {
#this.Model.User.NewsletterOnly.Equals(false);
});
});
The controller code for View's reset password panel:
[AllowAnonymous]
[HttpGet]
public ActionResult EditPassword(int userId, string token)
{
User user = new User();
EditUserViewModel top = new EditUserViewModel();
int rer = top.UserId;
userId = user.Id;
token = UserManager.GeneratePasswordResetToken(user.Id);
var model = new EditUserViewModel()
{
UserId = userId,
Token = token
};
return RedirectToAction("Edit", new { userId = userId });
}
//POST: /Admin/UserManager/Edit
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditPassword(EditUserViewModel model)
{
model.Token = UserManager.GeneratePasswordResetToken(model.UserId);
var user = this.UserManager.FindById(model.UserId); //Gets current user
var oldTermsAndConditionAgreement = user.TermsAndConditionsAgreement; //Gets current value of TermsAndConditionsAgreement
user.TermsAndConditionsAgreement = true; //Sets TermsAndConditionsAgreement to true
//Run a break on this line next time when coding
var result = this.UserManager.ResetPassword(model.UserId, model.Token, model.Password.Trim()); //If TermsAndConditionsAgreement is not true, this seems to break
user.TermsAndConditionsAgreement = oldTermsAndConditionAgreement; //TermsAndConditionsAgreement is set back to original value after process runs
if (result.Succeeded)
{
TempData["Message"] = AppResources.Common.FormAdminPasswordresetSuccess;
//return RedirectToAction("Login", "Account");
await _db.SaveChangesAsync();
//return RedirectToAction("Edit");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
return RedirectToAction("Edit", new { id = model.UserId });
}
I want to give 'Reset' button on the password panel the ability to display model panel if user has "newsletteronly" check-box set to "true".Which I can do by placing this Razor if statement syntax around modal code above.
*when Newsletteronly is set to true and checked account is not really a account so admin can't reset user's password, because no password is created in database for users who choose to receive news-letter. Other data like email, name, street address are collected and stored in DB. Email is username in this web-application.
#if (this.Model.User.NewsletterOnly == true)
{}
Doing this only allows the modal to display when reset button is clicked and if user's account meet the condition. The issue I'm having now is in trying to get
model to update for "NewsletterOnly" value to false when 'Continue' button is clicked on modal dialog after page-loads and modal disappears. I believe Ajax post can resolve this but don't know how to implement this with bootsrap modal on MVC 5 Razor .Net.
Images:
("Page View") description:Left side of view is "user panel" it displays 'NewsletterOnly' checkbox and it is checked as True if user has a news letter only account) Right side displays reset password panel and other panels
Modal
$("#btn-updateNL").on('click', function (e) {
$.post("yourActionMethodToUpdateNewsLetterValue",{userId:1,NL:false},function(){
alert('updated succesully');
});
});
where {userId:1,NL:false} here you need to pass the current users Id and then pass the value for NewsLetterOnly variable ie: NL as false. You can have a controller method which accepts these two parameters and then write your logic to update the Db.
Controller Action method would be something like
public async UpdateUserNewsLetterFlag(int userId,bool NL)

How to dynamically append templates to a page in Angular

So the situation is as follows:
I have an input bar where a user can search up a business name or add a person's name (and button to select either choice). Upon hitting enter I want to append a unique instance of a template (with the information entered by the user added). I have 2 templates I've created depending of if the user is searching for a business or a person.
One approach I've thought about is creating an object with the data and adding it with ng-repeat, however I can't seem to get the data loaded, and even then don't know how I can store reference to a template in my collection.
The other idea I've come across is adding a custom directive. But even then I've yet to see an example where someone keeps appending a new instance of a template with different data.
Here is the code so far:
payments.js:
angular.module('payment-App.payments',['ngAutocomplete'])
.controller('paymentController', function($scope, $templateRequest/*, $cookieStore*/) {
$scope.businessID;
$scope.address;
$scope.isBusiness = false;
$scope.payees = [];
$scope.newPayee = function () {
this.businessID = $scope.businessID;
this.address = $scope.address;
}
$scope.submit = function () {
var text = document.getElementById("businessID").value.split(",");
$scope.businessID = text[0];
$scope.address = text.slice(1).join("");
$scope.newPayee();
}
$scope.addPayee = function () {
$scope.submit();
$scope.payees.push(new $scope.newPayee());
console.log($scope.payees);
}
$scope.selectBusiness = function () {
//turns on autocomplete;
$scope.isBusiness = true;
}
$scope.selectPerson = function () {
//turns off autocomplete
$scope.isBusiness = false;
}
$scope.fillAddress = function () {
// body...
}
})
.directive("topbar", function(){
return {
restrict: "A",
templateUrl: 'templates/businessTemplate.html',
replace: true,
transclude: false,
scope: {
businessID: '=topbar'
}
}
})
payments.html
<h1>Payments</h1>
<section ng-controller="paymentController">
<div>
<div class="ui center aligned grid">
<div class="ui buttons">
<button class="ui button" ng-click="selectBusiness()">Business</button>
<button class="ui button arrow" ng-click="selectPerson()">Person</button>
</div>
<div class="ui input" ng-keypress="submit()">
<input id="businessID" type="text" ng-autocomplete ng-model="autocomplete">
</div>
<div class="submit">
<button class="ui button" id="submit" ng-click="addPayee()">
<i class="arrow right icon"></i>
</button>
</div>
</div>
<div class="search"></div>
<div class="payments" ng-controller="paymentController">
<li ng-repeat="newPayee in payees">{{payees}}</li>
</div>
<!-- <topbar></topbar> -->
</div>
(example template)
businessTemplate.html:
<div class="Business">
<div class="BusinessName" id="name">{{businessID}}</div>
<div class="Address" id="address">{{address}}</div>
<button class="ui icon button" id="hoverbox">
<i class="dollar icon"></i>
</button>
</div>
I ended up using a workaround with ng-repeat here. Still curious about the original question though.

Categories

Resources