Set ng-click attribute value from a string variable - javascript

I have an external JSON file which is a collection of buttons/actions like this
{
"foo1":{
"name":"productDetails",
"displayAs":"button",
"action":"viewDetails()"
},
"foo2":{
"name":"sell",
"displayAs":"button",
"action":"sellProduct()"
}
}
Later, in my view, I create a <div> using ng-repeat for each object contained in that JSON.
My question is, can I set the ng-click property as it it in the JSON file like this?
<li ng-repeat = "field in fields">
<div ng-click = field.action > {{field.name}} </div>
</li>

you can do this using ng-bind-html.
<li ng-repeat = "field in fields">
<div bind-html-compile ng-bind-html="trust(field)" > </div>
</li>
Add bind-html-compile directive to compile the DOM so that changes will effect to DOM elements
Directive
.directive('bindHtmlCompile', ['$compile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(function() {
return scope.$eval(attrs.bindHtmlCompile);
}, function(value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
In trust function pass the object as an argument and return the html trust element
$scope.trust = function(html) {
return $sce.trustAsHtml('<div ng-click = "' + html.action + '" > {{field.name}} </div>');
}
Demo
angular.module("app",[])
.controller("ctrl",function($scope,$sce){
$scope.viewDetails = function(){console.log("viewDetails")}
$scope.sellProduct = function(){console.log("sellProduct")}
$scope.fields = {
"foo1":{
"name":"productDetails",
"displayAs":"button",
"action":"viewDetails()"
},
"foo2":{
"name":"sell",
"displayAs":"button",
"action":"sellProduct()"
}
}
$scope.trust = function(html){
return $sce.trustAsHtml('<div ng-click = "'+html.action+'" > {{field.name}} </div>');
}
}).directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<li ng-repeat = "field in fields">
<div bind-html-compile ng-bind-html="trust(field)" > </div>
</li>
</div>

Related

In Angular 1.x how can I access controller methods from a custom directive?

I am currently trying to figure out the best way to access two controller methods from within my custom directive. My current code looks like so:
Parent Component Template (navMenus.html):
<menu-toggle section="navItem" ng-if="navItem.type === 'toggle'"></menu-toggle>
Parent Component Controller (navMenus.controller.js):
...
isOpen(section) {
return this.NavMenusFactory.isSectionSelected(section);
}
toggleOpen(section) {
this.NavMenusFactory.toggleSelectSection(section);
}
...
Directive Template (menuToggle.html):
<md-button class="md-button-toggle" ng-click="vm.toggle()">
{{ section.text | translate }}
</md-button>
<ul ng-show="vm.isOpen()" class="menu-toggle-list">
<li ng-repeat="subItem in section.subItems">
{{ subItem.text | translate }}
<menu-link section="subItem"></menu-link>
</li>
</ul>
Directive (menuToggle.directive.js):
...
return {
restrict: 'AE',
template,
replace: true,
scope: {
section: '=',
},
link(scope, element) {
$timeout(() => {
const $element = element;
scope.vm.toggle = function () {
console.log(scope.$parent.isOpen());
};
scope.isOpen = function () {
return $element.isOpen(scope.section);
};
scope.toggle = function () {
$element.toggleOpen(scope.section);
};
});
}
}
How can I access these methods?
Since there is scope in your directive, you have created an isolated scope.
So in order order to access the controller's function you can make use of events
Inside directive, create an $emit event, on the click event:
scope.toggle = function toggle (){
scope.$emit('EVENT_NAME', { data: true }) // here data is optional
}
In controller, you can perform action as:
$scope.$on('EVENT_NAME', function(event, data){
// here you can call the controller's method
})
This is the best way i know, to call a controller function from directive.
/* Directive template */
<md-button class="md-button-toggle" ng-click="vm.toggle()">
{{ section.text | translate }}
</md-button>
<ul ng-show="isOpen()" class="menu-toggle-list">
<li ng-repeat="subItem in section.subItems">
{{ subItem.text | translate }}
<menu-link section="subItem"></menu-link>
</li>
</ul>
/* Directive Code */
...
return {
restrict: 'AE',
template,
replace: true,
scope: {
section: '=',
isOpen: '&'
},
link(scope, element) {
$timeout(() => {
const $element = element;
scope.vm.toggle = function () {
console.log(scope.$parent.isOpen());
};
scope.isOpen = function () {
return $element.isOpen(scope.section);
};
scope.toggle = function () {
$element.toggleOpen(scope.section);
};
});
}
}
/* in your view, you can call controller fn */
<menu-toggle section="navItem" is-open="isOpen()" ng-if="navItem.type === 'toggle'"></menu-toggle>

how can get ng-model value within ng-repeat on directive?

I want's to get the value of ng-model within the the ng-repeat on my own directive and use the value of that ng-model in the directive for a fuction.
here is a plunker to see code in action :
https://plnkr.co/edit/MaI8DOtdc4yucXgNo05p?p=preview
here is my directive code :
(function() {
'use strict';
angular.module('barname.rtEditor', [])
.directive('rtEditor', rtEditor);
function rtEditor() {
return {
restrict: 'E',
replace: true,
templateUrl: 'rt-ht.html',
compile: compile
};
function compile() {
return {
post: function(scope, element, attrs) {
scope.com = {
inp: [{
name: 'video',
model: scope.vimodel,
command: 'insertHTML',
modelcommand: scope.vimodel
}, {
name: 'pic',
model: scope.pimodel,
command: 'insertImage',
modelcommand: scope.pimodel
}, {
name: 'link',
model: scope.linkmodel,
command: 'createLink',
modelcommand: scope.linkmodel
}]
};
scope.$watch('vimodel', function(newValue, oldValue) {
console.log('vim model watch :-> ', newValue);
});
scope.$watch('texmodel', function(newValue, oldValue) {
console.log('text model watch :-> ', newValue);
});
scope.execIn = function(cmd, val) {
console.log('cmd val :->', cmd + ' | ' + val);
scope.vimodel = '';
scope.texmodel = '';
};
}
};
}
}
})();
and here is the html code :
<div>
<div ng-repeat="inp in com.inp" id="{{inp.name}}">
<label>{{inp.name}} :</label>
<input type="text" ng-model="inp.model" />
<span ng-click="execIn(inp.command, inp.modelcommand)">doIt!</span>
</div>
<br>
<hr>
<br>
<div>
<label>widout ng repeat:</label>
<input type="text" ng-model="texmodel" />
<span ng-click="execIn('textIn', texmodel)">doIt!</span>
</div>
</div>
I can easily get the value of the ng-model without ng-repeat

Calling a init function when a directive is loaded

I have a simple directive that loads comments from a service(commentsService):
'use strict';
angular.module('mean.rank')
.directive('commentList', function(CommentsService, Global) {
return {
restrict: 'E',
templateUrl: 'rank/views/comments-list.html',
replace: false,
link: function($scope, element, attrs) {
//accessing the ad info : console.log("ADD " , $scope.ad);
$scope.comments = [];
$scope.loadComments = function () {
console.log("in loadComments");
var adID = {};
adID.ad_ID = $scope.ad.nid;
console.log("calling services.getComments function with " , adID.ad_ID);
CommentsService.getComments(adID.ad_ID)
.then(function (response) {
angular.forEach(comment in response)
$scope.comments.push(comment);
});
};
}
}
})
The loaded comments should be loaded to the list(inside the templateUrl) using ng-init and then the service for loading (I will add the code if needed).
<div ng-init="loadComments()">
<ul class="media-list comment-detail-list" >
<li class="media" ng-repeat="comment in comments" >
<article>
<div class="pull-left comment-info">
{{ comment.author }}<br />
<time>{{ comment.datePublished | date:"MM/dd/yyyy" }}</time>
</div>
<div class="media-body">
<div class="comment-body">
<p>{{ comment.comment }}</p>
</div>
</div>
</article>
</li>
<li>Debugger</li>
</ul>
</div>
The directive has in its scope the loadCommets() function but it is not triggered.
Thank's for your help!
I'd suggest putting the function call inside the link function itself instead of ng-init.
angular.module('mean.rank')
.directive('commentList', function(CommentsService, Global) {
return {
...
link: function($scope, element, attrs) {
//accessing the ad info : console.log("ADD " , $scope.ad);
$scope.comments = [];
$scope.loadComments = function () {
...
};
$scope.loadComments();
}
}
})
Edit: by the way your forEach syntax is wrong. It should be
angular.forEach(response, function(comment){
$scope.comments.push(comment);
});

AngularJS - Fill input text field with dropdown menu

How can I fill an input text field with a dropdown-menu ?
Text Input:
<input type="text" ng-model="storagePlaceModel" lms-dropdown class="form-control lms-input-text-disable lms-dropdown-toggle" id="storagePlace" placeholder="Standort" autocomplete="off" readonly>
Own written dropdown:
<div class="lms-dropdown">
<div class="lms-dropdown-scrollbar">
<li ng-repeat="data in data_input_fields.input_cat_music_book_storage_place">
<span>{{data.input_value}}</span>
<i ng-show="storagePlaceModel == data.input_value" class="glyphicon glyphicon-ok"></i>
</li>
</div>
</div>
If I select an li element I want to update the storagePlaceModel with the li value.
Updated question:
Because I have more than one of these text inputs with dropdowns I need a solution where the conroller/directive does not know the model name exactly.
Directive could look like:
lmsApp.directive('updateInputField', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
$(elem).click(function(e) {
// Read out the model name of the html text input field
});
}
};
});
Thank you for your help! I would appreciate every answer.
I've edited the entire question to create a directive to wrap your desired structure. You'll pass to the directive the model you want, and that way, each model will be independent on different directive usages:
myApp.directive('myDirective', function() {
return {
restrict: "E",
scope: {
model: "=",
datas: "="
},
templateUrl: "directive.html",
link: function(scope, element, attr) {
scope.updateValue = function(val) {
scope.model.storagePlaceModel = val;
}
}
}
});
The directive.html contains your text input and the dropdown.
Controller:
function MyCtrl($scope) {
$scope.wrapper = {};
$scope.wrapper2 = {};
$scope.wrapper3 = {};
$scope.datas = [
{ "input_value" : "1" },
{ "input_value" : "2" },
{ "input_value" : "3" },
{ "input_value" : "4" }
];
}
HTML usage:
<div ng-app="myApp" ng-controller="MyCtrl">
<my-directive model="wrapper" datas="datas"></my-directive>
<my-directive model="wrapper2" datas="datas"></my-directive>
<my-directive model="wrapper3" datas="datas"></my-directive>
</div>
Working Fiddle

How to change input's ngModel source from the directive?

I want to change the source (e.g source variable) that is managed by input's ngModel from my directive.
I want to clone the object that is editable by a form and make this process in the directive.
Probably this jsfiddle will explain you better.
What I do is:
<div ng-app="myApp">
<div ng-controller="SimpleController">
<form change-original-model>
<input ng-model="myModel.firstname" /><br/>
<input ng-model="myModel.secondname" /><br/>
I want <b>myModel</b> to be not changed:<br/>
{{ myModel.firstname }}<br/>
I want <b>newModel</b> to be cloned and changed by input:<br/>
{{ newModel.firstname }}<br/>
</form>
</div>
angular.module('directives', []);
angular.module('directives').controller('SimpleController', function($scope) {
$scope.myModel = { firstname: 'Sady', secondname: 'Sherozi' };
});
angular.module('directives').directive('changeOriginalModel',
function($parse) {
return {
require: '?ngModel',
link: function(scope, element, attrs, controller) {
var ngModel = $parse(attrs.ngModel)(scope);
scope.newModel = angular.copy(ngModel);
$(element).find("input").each(function(){
form_elements = $(this).attr("ng-model");
if (form_elements) {
var replace_input_data = form_elements.replace(attrs.ngModel + '.', "newModel." );
$(this).attr("ng-model", replace_input_data);
}
});
}
};
}
);
angular.module('myApp', ['directives']);

Categories