Call function within object as parameter for a directive - javascript

currently I'm extending my application, so I can give a directive (which generates a table grid) an object for additional buttons to show (for adding other other actions).
Now I can show the button but I need to execute some code as function which should be apply for a click on that button.
The object itself contains strings and function in a mixed way, like this:
<tablegrid
table="flavorings"
additional-buttons="[{name: 'add', onclick: 'function(){ }', icon: 'fa fa-plus'}]"
show-actionbutton="true"
show-rating="true"
show-search="true"
show-rowcheckbox="true"
show-header="true">
</tablegrid>
My directive template looks like this:
<button ng-repeat="aB in additionalButtons" class="btn btn-primary" ng-click="ab.onclick" type="button">
<i ng-class="aB.icon" ng-show="aB.icon != ''" aria-hidden="true"></i>
<span>{{ 'TABLEGRID_'+aB.name | uppercase | translate }}</span>
</button>
How can I execute the onclick-function?

You can directly call a function of an object of the scope in your view with:
ng-click="yourObject.functionName(parameters)"
Don't forget the parenthesis in the function call even if there is no parameters
Here is a demo of how it works:
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
$scope.additionalButtons = [
{'name': 'First',
'onclick': function() {alert('1')}
},
{'name': 'Second',
'onclick': function() {alert('2')}
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-repeat="ab in additionalButtons" ng-click="ab.onclick()">Click {{ab.name}}</button>
</div>

Related

ng-click function is not called with onclick in a AngularJS?

I have to call the ng-click function with the onClick but in my case ng-click function is not
//Controller function
$scope.editProductDetail = function(productObject) {
$scope.getProduct = productObject;
}
<a href="#"
onclick="document.getElementById('editProduct').style.display='block'" ng-click="editProductDetail(list)" target="_self">
</a>
call but model is open with onClick function?
It seems you're trying to set a class to the selected item from a product list, it seems you're confusing some AngularJS concepts.
If you're using AngularJS there's no need to use both onclick and ng-click.
If you want to show all products from your list you may want to use ng-repeat.
You need to initialize your Module for your AngularJS controller to load, and the controller must be within the module in the HTML code.
I've done an example bellow based on your code, it might help if you edit your answer and add your complete code.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.selectedIndex = 0;
$scope.editProductDetail = function (index) {
$scope.selectedIndex = index;
};
$scope.productList = [
{ name: 'Product 1', price: '1,00 U$' },
{ name: 'Product 2', price: '2,00 U$' },
{ name: 'Product 3', price: '3,00 U$' }
];
});
.selected-item {
display: block;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" >
<h2>Selected Item Number: {{ selectedIndex + 1}}</h2> <!-- I've added +1 since index starts at 0 -->
<div ng-repeat="item in productList">
{{ item.name}} {{item.price}}
</div>
</div>
As debabrata was saying you don't need to use both, just use something like this:
// Your controller
$scope.editProductDetail = function(productObject) {
$scope.setDisplayBlock = true;
$scope.getProduct = productObject;
}
// Your HTML
<span id="editProduct" ng-class="{'css-class-with-display-block': setDisplayBlock}">The element to change</span>

How to create a new directive that will compile other directive attributes in Angularjs?

I am trying to create buttons (using ng-repeat) that when clicked will create other buttons that when these are clicked will display the information I am looking for. I was told that an Angular Directive would do the trick. I have created a custom directive and am trying to incorporate the ng-repeat directive inside of my new directive. I have already looked at this StackOverflow discussion StackOverflow Discussion 2, but I am still having some confusion on how to best get his implemented. As it stands the new directive is being made, but no text is being appended to the button. Also only one button is being generated instead of two in this case. Below is my code (HTML and JavaScript)
HTML:
<div ng-app="anniversaries" class="row" ng-controller="annList">
<yearbuttons></yearbuttons>
</div>
JavaScript:
var annApp = angular.module('anniversaries', []);
annApp.controller('annList', function ($scope) {
$scope.anns = [
//January
{'date':'January 2015','year': '45',
'names': ['Sample Name']},
{'date':'January 2015','year': '34',
'names': ['Sample Name2']}
];
});
annApp.directive('yearbuttons',function(){
return {
restrict: "E",
compile: function compile(element, attrs)
{
element.attr('ng-repeat', 'years in anns');
element.attr('class', 'btn btn-default');
element.append('{{year}} Years');
}
}
});
I personally wouldn't use a directive for this at all unless it needed to be used repeatedly. But if it does, this could easily be converted to a directive just by sticking the template and controller into a directive. Directives can take controllers instead of link functions.
JavaScript
(function(){
angular.module('myApp', [])
.controller('BunchOfButtonsController', BunchOfButtonsController);
BunchOfButtonsController.$inject = ['$scope', '$log'];
function BunchOfButtonsController($scope, $log){
$scope.buttons = [];
$scope.nextLabel = "Some Text";
$scope.firstButtonClick = function(labelValue){
$scope.buttons.push({
label: labelValue,
click: function(){
$log.info(labelValue + " was clicked.");
}
});
$scope.nextLabel = "Another " + $scope.nextLabel;
};
}
})();
HTML
<div ng-app="myApp" ng-controller="BunchOfButtonsController">
Label: <input type="text" ng-model="nextLabel"/>
<button ng-click="firstButtonClick(nextLabel)">Click Me!</button>
<button ng-repeat="button in buttons" ng-click="button.click()">{{button.label}}</button>
</div>

ng-click does not work

I'm programming a single-page web application, mostly using the AngularJS framework, and am encountering a problem while using the ng-click directive.
This directive actually does nothing upon click. The linked method is not called (I can't debug it).
Below the code in question:
template file:
<div ng-controller="BonusCtrl as bonusManager">
<!-- [...] -->
<button style="margin-top: 5px"
class="btn btn-success" ng-click="add()"><i class="fa fa-plus"/> Règle de calcul</button>
<!-- [...] -->
</div>
controller:
idServerApp.controller('BonusCtrl', ['$scope', 'webService', 'math', 'DATERANGE_OPTIONS', function ($scope, webService, math, DATERANGE_OPTIONS) {
$scope.add = function() {
console.log('foo'); // no call
var newItem = {
brandId: undefined,
days: 0,
priceMinEVAT: 0,
bonus: 0
};
$scope.rules.push(newItem);
};
Do you have any idea of the problem?
Edit 1
I tried to replace bonusManager.add() by add() and BonusCtrl.add().
I then tried to replace $scope by this, or to remove the controllerAs.
Complete JSFiddle (using some of my services)
Edit 2
Thanks for your answers. I found the solution myself, and it was crappy.
I forgot a closing div tag in the HTML template, so the controller was not defined.
I get your code and made an running example with two cases.
First one using BonusCtrl
$scope.add = function () {...}
ng-click="add()"
And second with bonusManager
this.add = function () {...}
ng-click="bonusManager.add()"
For me it should works just fine. Please let me know if you have any other issues.
var app = angular.module('myapp',[]);
app.controller('BonusCtrl', ['$scope', function ($scope) {
$scope.add = function() {
console.log('Hey you\'ve just invoked add() function!'); // no call
var newItem = {
brandId: undefined,
days: 0,
priceMinEVAT: 0,
bonus: 0
};
};
this.add = function () {
console.log('You can invoke function using \' bonusManager.add()'); // no call
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<h1>NG-CLICK EXAMPLE</h1>
<div ng-controller="BonusCtrl as bonusManager">
<button style="margin-top: 5px"
class="btn btn-success" ng-click="add()"><i class="fa fa-plus"/>add()</button>
<button style="margin-top: 5px"
class="btn btn-success" ng-click="bonusManager.add()"><i class="fa fa-plus"/> bounsManager.add()</button>
</div>
</div>
However you can always use your
Check the working demo: JSFidde
You are using <div ng-controller="BonusCtrl as bonusManager">, so call it like:
<button style="margin-top: 5px" class="btn btn-success"
ng-submit="bonusManager.add()"><i class="fa fa-plus"/> Règle de calcul</button>
In the controller, define this.add = function() {... instead of $scope.add = function() {.... Because the keyword as will call a new BonusCtrl() under the hood.
If you use $scope than you don't need construction ControllerAs, just use
<div ng-controller="BonusCtrl">
and submit function ng-submit="add()"
Or if you want to use ControllerAs, than use "this":
<div ng-controller="BonusCtrl as bonusManager">
ng-submit="BonusCtrl.add()"
But in your controller have to be "this" instead of $scope:
`
this.add = function() {
`
Try it.
If you are using BonusCtrl as bonusManager then do as follows
Update bonusManager.add() in view and in controller write this.add instead of $scope.add() .
Otherwise just remove as bonusManager from ng -controller syntax .it will work fine.

AngularJS remove last element of array in scope

I have my controller in Angular which contains an array and a delete method
function($scope, $http){
$scope.arrayOfObjects = [];
$scope.remove = function(obj){
var i = $scope.arrayOfObjects.indexOf(obj);
if( i > -1 ){
$scope.arrayOfObjects.splice(i, 1);
}
}
// Some other things
}
HTML
<a href ng-repeat="(key, obj) in arrayOfObjects track by $index">{{obj.id}}
<button type="button" role="button" class="btn btn-default" ng-click="remove(obj)">
<i class="fa fa-trash"></i>
<span>Delete</span>
</button>
</a>
Now all works well when I delete an object other than the last. When the user presses on the delete button for the last object, the page gets redirected to localhost:3000/# which is not mapped to anything and I get a blank page.
Has anyone encountered such behavior?
While the other answers are addressing your link / redirect issue, which would be solved by not having additional clickable items inside an anchor tag, the bigger problem is that you're using the wrong syntax for iterating over the objects of an array.
To iterate over an array you want this:
ng-repeat="obj in arrayOfObjects"
The syntax you're using is for iterating over the properties of one single object. Where key and value are the arguments passed to your repeater
ng-repeat="(key, value) in object"
Most likely what you want is something like this:
<div ng-repeat="obj in arrayOfObjects">
{{obj.id}}
<button ng-click="remove(obj)">Delete</button>
</div>
codepen
You can use 'filter' to return to original scope all itens that you want, just like that:
$scope.remove = function (objs) {
$scope.objs = objs.filter(function (obj) {
//Here you remove the item you do not want
return obj;
});
};
Html:
<button class="btn btn-danger btn-block" ng-click="remove(objs)">Delete</button>
Last element can be removed by using pop() and returns that element like $scope.arrayOfObjects.pop()
angular.module('app', [])
.controller('mycontroller', function($scope) {
$scope.arrayOfObjects = [{ id: 1 }, { id: 2 }, { id: 3 }]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="mycontroller">
<button ng-click="arrayOfObjects.pop()">remove in inline</button>
<ul>
<li ng-repeat="myobj in arrayOfObjects">{{myobj.id}}</li>
</ul>
</div>

How can you pass a bound variable to an ng-click function?

I have a simple delete button that will accept a string or number but won't accept an ng-model variable ( not sure if that's the correct terminology ).
<button class="btn btn-danger" ng-click="delete('{{submission.id}}')">delete</button>
Which generates:
<button class="btn btn-danger" ng-click="delete('503a9742d6df30dd77000001')">delete</button>
However, nothing happens when I click. If I hard code a variable then it works just fine. I assume I'm just not doing things the "Angular" way, but I'm not sure what that way is :)
Here's my controller code:
$scope.delete = function ( id ) {
alert( 'delete ' + id );
}
You don't need to use curly brackets ({{}}) in the ng-click, try this:
<button class="btn btn-danger" ng-click="delete(submission.id)">delete</button>
The ngClick directive binds an expression. It executes Angular code directly (as ngIf, ngChange, etc.) without the need of {{ }}.
angular.module('app', []).controller('MyCtrl', function($scope) {
$scope.submission = { id: 100 };
$scope.delete = function(id) {
alert(id + " deleted!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<button ng-click="delete(submission.id)">Delete</button>
</div>

Categories

Resources