Angular5 Bindings not working with function call in object [hidden] - html

I currently have the hidden attribute of one of my divs binded to a boolean in my typescript. But, when I am changing the value of the boolean in one of my function calls nested within an object the dom is not updating on the front end?
typescript
hideSymbols = true;
bindings = {
enter: {
key: 13,
handler: function() {
console.log('enter pressed');
this.hideSymbols = !this.hideSymbols;
console.log(this.hideSymbols);
}
}
};
html
<div [hidden]="hideSymbols">
<button id="equalsBtn" class="symbolBtn">=</button>
<button id="impliesBtn" class="symbolBtn">=></button>
</div>
It works if I am not making the call in this handler but I need to in order for my ngx-quill instance to update how the enter key works. Essentially, why is hideSymbols getting updated but on my web view the element does not disappear and reappear?

Make that:
handler: () => {...
...rather than use function. A function defined using function has its own this.
I'm not sure this is the whole problem without more context, but it's probably at least part of the problem.

this.hideSymbols = !this.hideSymbols; is executing in the wrong scope.
This is what you have:
var result1 = null;
var exhibitA = {
execute: function(){
this.result1 = "hello";
}
};
exhibitA.execute();
console.log({ exhibitA, result1 });
This is what you want:
var result2 = null;
var exhibitB = {
execute: () => {
this.result2 = "hello";
}
};
exhibitB .execute();
console.log({ exhibitB, result2 });

Related

Call an action from a Html.Dropdown onchange event in ASP.Net MVC 5

I'm trying to call the action in the controller when the dropdown selected item changes. Here is the code I am using but it is not working.
#Html.DropDownList("UserID", null, new { #onchange = "location.href='#Url.Action("Action", "Controller")'" })
What is the correct syntax? I tried to call a javascript function and it works.
#Html.DropDownList("UserID", null, new { #onchange = "leaveChange(this);" })
leaveChange(control) is my javascript function.
However, I am unable to invoke the action of the controller. Also, How do I then pass the value of the selected item to the action?
You cannot call a C# method inside the htmlAttributes object where it expects a key value pair. Instead you could execute the Url.Action method and set the result(the url) on a parent element's data attribute and read from that in your javascript code
<div data-submit-url="#Url.Action("ApplyVacation","Jobs")">
#Html.DropDownList("UserID",)
</div>
and in the change event, read it
$(document).ready(function ()
{
$("#UserID").change(function ()
{
var $this = $(this);
var url = $this.parent().data("submit-url") + "?userId=" + $this.val();
window.location.href = url;
});
});
When user make a selection on the SELECT, this code will navigate to the /Jobs/ApplyVacation url with querystring key userId and the selected option value as the value of that. Update the names as needed based on your code.
Try removing # before onchange
#Html.DropDownList("UserID", null, new { onchange = "location.href='#Url.Action("Action", "Controller")'" })
If you want to pass parameters to action you can use
#Html.DropDownList("UserID", null, new { onchange = "location.href='#Url.Action("Action", "Controller",
new {name = "Test param", category = "Test1"})'" })
Here is what I did
#Html.DropDownList("UserID", null,new {#id = "leve" })
Jquery code as below:
<script type="text/javascript">
$('#leve').change(function () {
var url = "/UserRoles/TellMeDate";
var name = $('#leve').val();
$.get(url, { parameter: name }, function (data) {
alert(data);
});
})
});
</script>
Controller:
public string TellMeDate(string parameter)
{
return DateTime.Today.ToString() +"-->>>"+ parameter + "!!!!";
}
This code worked for me:
onchange = "location.href='" + #Url.Action("AdmissionRequirement", "Profile") + "'"

AngularJS: Dynamically change expression after $watch

The main thing I want to do here is:
When the form is submitted, a http get request will be done (VerbController)
On success, a JSON string is returned
I copy the JSON string into a factory object (called VerbFactory)
I want to output the content of the JSON string in a div through another controller (OutputController), I took the attribute "name" as an example here.
To achieve this (point 4), I watched for a change in the VerbFactory object and when the JSON string after requesting gets loaded into the object, I want to store it in a variable of the OutputController, so that I can make an expression for it in my HTML.
But it does not work right now. It seems that this.verb is in another scope than the controller scope. I have difficulties understand the difference between $scope and this here, even though I have read a decent amount of articles about the difference between those two.
How do I solve this problem? Do I miss something obvious?
NB: I added some jQuery that puts the attribute "name" of the JSON into a debug div, and it works as expected. But the AngularJS expression {[{outputCtrl.verb["#attributes"]["name"]}]} does not work.
HTML:
<div class="container">
<div class="row">
<div id="debug" class="col-xs-12 col-sm-12">
</div>
<div class="col-xs-12 col-sm-12" ng-controller="OutputController as outputCtrl">
{[{outputCtrl.test}]}
{[{outputCtrl.verb["#attributes"]["name"]}]}
</div>
</div>
</div>
JS:
(function() {
var app = angular.module('LG', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
});
app.factory("VerbFactory", function(){
var json = {};
var available = false;
return {
getJSON: function() {
return json;
},
setJSON: function(newObj) {
angular.copy(newObj, json);
available = true;
},
isAvail: function() {
return available;
},
resetAvail: function() {
available = false;
}
};
});
app.controller("VerbController", ['$http', 'VerbFactory', function($http, VerbFactory){
this.verb = "";
this.requestVerb = function() {
VerbFactory.resetAvail();
var that = this;
$http.get('/request/' + that.verb).
success(function(data) {
VerbFactory.setJSON(data);
}).
error(function() {
});
this.verb = "";
};
}]);
app.controller("OutputController", ['$scope', 'VerbFactory', function($scope, VerbFactory){
this.test = "Test!";
$scope.$watch(VerbFactory.isAvail, function(){
this.verb = VerbFactory.getJSON();
$('#debug').append('<p>'+ this.verb["#attributes"]["name"] +'</p>');
});
}]);
})();
this inside of $scope.$watch callback refers to the callback scope, not the outer scope of OutputController. Use var self = this to refer to the OutputController.
ControllerAs Syntax
OutputController.js
var self = this
$scope.$watch(VerbFactory.isAvail, function(){
self.verb = VerbFactory.getJSON();
//etc
});
Regular Controller Syntax
OutputController.js
$scope.$watch(VerbFactory.isAvail, function() {
$scope.verb = VerbFactory.getJSON();
//etc
});

Knockout: Mapping/binding JSON

I'm new to knockout. I'm trying to bind the json returned from ajax call but it isn't happening.
<script type="text/javascript">
var ServerData;
$(document).ready(function () {
ko.setTemplateEngine(new ko.nativeTemplateEngine);
var oViewModel = new CompanyModel();
oViewModel.Newitem(new Company("","","","","","","","","","","","","","",""));
ko.applyBindings(oViewModel);
BasicDatatable('#TableCompany');
});
function CompanyModel() {
var self = this;
self.CompanyList = ko.observable();
$.getJSON("getallcompanies", function (response) {
ServerData = ko.mapping.fromJSON(response);
self.CompanyList(ServerData);
});
}
In response I've the required data. But in ServerData I'm getting the following instead of the list.
function b() { if (0 < arguments.length) { if (!b.equalityComparer || !b.equalityComparer(d, arguments[0])) b.H(), d = arguments[0], b.G(); return this } r.T.Ha(b); return d }
Can You please let me know what's going wrong?
You should use ko.mapping.fromJS to bind JSON that comes from server.
Also, you don't need to define self.CompanyList = ko.observable(); and bind set value to that property in self.CompanyList(ServerData);.
It's all done by ko.mapping.fromJS. From Knockout Mapping documentation:
All properties of an object are converted into an observable. If an
update would change the value, it will update the observable.
Arrays are converted into observable arrays. If an update would
change the number of items, it will perform the appropriate
add/remove actions. It will also try to keep the order the same as
the original JavaScript array.
Try to change code like this:
function CompanyModel() {
var self = this;
$.getJSON("getallcompanies", function (response) {
ko.mapping.fromJSON(response, {}, self);
});
}

view not gathering data from service through controller

Having trouble loading an external json file and having it's contents display on my view. I've included my view, controller and services code. What do I need to change?
view.html
<div ng-controller='BaseCtrl'>
<table class="table table-hover">
<tbody>
<tr class="tr-sep" ng-repeat="example in examples" ng-click="showUser(example)">
<td>{{example.name}}</td>
<td>{{example.type}}</td>
<td>{{example.size}}</td>
</tr>
</tbody>
</table>
</div>
controller.js
'use strict';
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, data) {
$scope.examples = data.getAllExamples();
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
service.js
'use strict';
angular.module('projyApp')
.service('data', function data() {
var examples;
var getAllExamples = function () {
$http.get("../../TestData/Examples.json").success($scope.examples = data.examples);
};
});
Your service code isn't correct. I see the following problems:
You're creating a local variable getAllExamples that's not accessible from outside the service;
You're using the $http service, but that dependency isn't expressed in the service constructor;
You're trying to update the scope from the service, but it's inaccessible from there. Plus, the $scope variable is not even defined inside the service code.
Here's how your service could look like:
.service('data', function($http) {
this.getAllExamples = function(callback) {
$http.get("../../TestData/Examples.json")
.success(function(data) {
if (callback) callback(data.examples);
});
};
});
And your controller code would be like this:
.controller('BaseCtrl', function ($scope, data) {
data.getAllExamples(function(examples) {
$scope.examples = examples;
});
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
You could ditch the callback in the getAllExamples function and work directly with the $http.getreturned promise, but that's a bit more complicated.
Update Added a Plunker script to illustrate the code above.
Main module definition should look like:
angular.module("projyApp",[/*dependencies go here*/]);
Service should look like
//this use of module function retrieves the module
//Note from comments in angular doc: This documentation should warn that "angular.module('myModule', [])" always creates a new module, but "angular.module('myModule')" always retrieves an existing reference.)
angular.module('projyApp')
.service('dataService', [/*dependencies,*/function() {
var service = {
examples:[],
getAllExamples = function () {
$http.get("../../TestData/Examples.json").success(function(returnedData){examples = returnedData});
}
}
return service;
});
Controller should look like:
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, dataService) {
$scope.examples = [];
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
$scope.$watch(function(){return dataService.examples}, function(newVal,oldVal) {$scope.examples = newVal});
});
Also you can add
debugger;
on an line to trigger Chrome to break (like a breakpoint but without having to dig through the scripts at run-time) so long as the Debugging Panel is open (F12)
You should use a callback instead of assigning in to a scope in you data service. By doing that, you can use this function in multiple controllers an assign values to appropriate scopes.
Data Service
var getAllExamples = function (callback) {
$http.get("../../TestData/Examples.json").success(function(data) {
if (typeof callback === "function") callback(data);
});
};
Controller
data.getAllExemples(function(data) {
$scope.examples = data;
});
EDIT
Another what is to create a promise object.
Data Service
var getAllExamples = function () {
return $http.get("../../TestData/Examples.json");
};
Controller
var promise = data.getAllExemples();
promise.then(function(data) {
$scope.examples = data;
});
EDIT 2
In your service, you need to return your functions
angular.module('projyApp')
.service('data', function data() {
var examples;
return {
getAllExamples: function () {
$http.get("../../TestData/Examples.json").success(...);
}
};
});

angularjs directive call function specified in attribute and pass an argument to it

I want to create a directive that links to an attribute. The attribute specifies the function that should be called on the scope. But I also want to pass an argument to the function that is determined inside the link function.
<div my-method='theMethodToBeCalled'></div>
In the link function I bind to a jQuery event, which passes an argument I need to pass to the function:
app.directive("myMethod",function($parse) {
restrict:'A',
link:function(scope,element,attrs) {
var expressionHandler = $parse(attrs.myMethod);
$(element).on('theEvent',function( e, rowid ) {
id = // some function called to determine id based on rowid
scope.$apply(function() {expressionHandler(id);});
}
}
}
app.controller("myController",function($scope) {
$scope.theMethodToBeCalled = function(id) { alert(id); };
}
Without passing the id I can get it working, but as soon as I try to pass an argument, the function is not called anymore
Marko's solution works well.
To contrast with recommended Angular way (as shown by treeface's plunkr) is to use a callback expression which does not require defining the expressionHandler. In marko's example change:
In template
<div my-method="theMethodToBeCalled(myParam)"></div>
In directive link function
$(element).click(function( e, rowid ) {
scope.method({myParam: id});
});
This does have one disadvantage compared to marko's solution - on first load theMethodToBeCalled function will be invoked with myParam === undefined.
A working exampe can be found at #treeface Plunker
Just to add some info to the other answers - using & is a good way if you need an isolated scope.
The main downside of marko's solution is that it forces you to create an isolated scope on an element, but you can only have one of those on an element (otherwise you'll run into an angular error: Multiple directives [directive1, directive2] asking for isolated scope)
This means you :
can't use it on an element hat has an isolated scope itself
can't use two directives with this solution on the same element
Since the original question uses a directive with restrict:'A' both situations might arise quite often in bigger applications, and using an isolated scope here is not a good practice and also unnecessary. In fact rekna had a good intuition in this case, and almost had it working, the only thing he was doing wrong was calling the $parsed function wrong (see what it returns here: https://docs.angularjs.org/api/ng/service/$parse ).
TL;DR; Fixed question code
<div my-method='theMethodToBeCalled(id)'></div>
and the code
app.directive("myMethod",function($parse) {
restrict:'A',
link:function(scope,element,attrs) {
// here you can parse any attribute (so this could as well be,
// myDirectiveCallback or multiple ones if you need them )
var expressionHandler = $parse(attrs.myMethod);
$(element).on('theEvent',function( e, rowid ) {
calculatedId = // some function called to determine id based on rowid
// HERE: call the parsed function correctly (with scope AND params object)
expressionHandler(scope, {id:calculatedId});
}
}
}
app.controller("myController",function($scope) {
$scope.theMethodToBeCalled = function(id) { alert(id); };
}
Not knowing exactly what you want to do... but still here's a possible solution.
Create a scope with a '&'-property in the local scope.
It "provides a way to execute an expression in the context of the parent scope" (see the directive documentation for details).
I also noticed that you used a shorthand linking function and shoved in object attributes in there. You can't do that. It is more clear (imho) to just return the directive-definition object. See my code below.
Here's a code sample and a fiddle.
<div ng-app="myApp">
<div ng-controller="myController">
<div my-method='theMethodToBeCalled'>Click me</div>
</div>
</div>
<script>
var app = angular.module('myApp',[]);
app.directive("myMethod",function($parse) {
var directiveDefinitionObject = {
restrict: 'A',
scope: { method:'&myMethod' },
link: function(scope,element,attrs) {
var expressionHandler = scope.method();
var id = "123";
$(element).click(function( e, rowid ) {
expressionHandler(id);
});
}
};
return directiveDefinitionObject;
});
app.controller("myController",function($scope) {
$scope.theMethodToBeCalled = function(id) {
alert(id);
};
});
</script>
You can create a directive that executes a function call with params by using the attrName: "&" to reference the expression in the outer scope.
We want to replace the ng-click directive with ng-click-x:
<button ng-click-x="add(a,b)">Add</button>
If we had this scope:
$scope.a = 2;
$scope.b = 2;
$scope.add = function (a, b) {
$scope.result = parseFloat(a) + parseFloat(b);
}
We could write our directive like so:
angular.module("ng-click-x", [])
.directive('ngClickX', [function () {
return {
scope: {
// Reference the outer scope
fn: "&ngClickX",
},
restrict: "A",
link: function(scope, elem) {
function callFn () {
scope.$apply(scope.fn());
}
elem[0].addEventListener('click', callFn);
}
};
}]);
Here is a live demo:
http://plnkr.co/edit/4QOGLD?p=info
Here's what worked for me.
Html using the directive
<tr orderitemdirective remove="vm.removeOrderItem(orderItem)" order-item="orderitem"></tr>
Html of the directive: orderitem.directive.html
<md-button type="submit" ng-click="remove({orderItem:orderItem})">
(...)
</md-button>
Directive's scope:
scope: {
orderItem: '=',
remove: "&",
My solution:
on polymer raise an event (eg. complete)
define a directive linking the event to control function
Directive
/*global define */
define(['angular', './my-module'], function(angular, directives) {
'use strict';
directives.directive('polimerBinding', ['$compile', function($compile) {
return {
restrict: 'A',
scope: {
method:'&polimerBinding'
},
link : function(scope, element, attrs) {
var el = element[0];
var expressionHandler = scope.method();
var siemEvent = attrs['polimerEvent'];
if (!siemEvent) {
siemEvent = 'complete';
}
el.addEventListener(siemEvent, function (e, options) {
expressionHandler(e.detail);
})
}
};
}]);
});
Polymer component
<dom-module id="search">
<template>
<h3>Search</h3>
<div class="input-group">
<textarea placeholder="search by expression (eg. temperature>100)"
rows="10" cols="100" value="{{text::input}}"></textarea>
<p>
<button id="button" class="btn input-group__addon">Search</button>
</p>
</div>
</template>
<script>
Polymer({
is: 'search',
properties: {
text: {
type: String,
notify: true
},
},
regularSearch: function(e) {
console.log(this.range);
this.fire('complete', {'text': this.text});
},
listeners: {
'button.click': 'regularSearch',
}
});
</script>
</dom-module>
Page
<search id="search" polimer-binding="searchData"
siem-event="complete" range="{{range}}"></siem-search>
searchData is the control function
$scope.searchData = function(searchObject) {
alert('searchData '+ searchObject.text + ' ' + searchObject.range);
}
This should work.
<div my-method='theMethodToBeCalled'></div>
app.directive("myMethod",function($parse) {
restrict:'A',
scope: {theMethodToBeCalled: "="}
link:function(scope,element,attrs) {
$(element).on('theEvent',function( e, rowid ) {
id = // some function called to determine id based on rowid
scope.theMethodToBeCalled(id);
}
}
}
app.controller("myController",function($scope) {
$scope.theMethodToBeCalled = function(id) { alert(id); };
}