Creating a Reusable Component in AngularJS - angularjs

I am new to Stackoverflow. I'm also new to AngularJS. I apologize if I'm not using this correctly. Still, I'm trying to create a UI control with AngularJS. My UI control will look like this:
+---------------------+
| |
+---------------------+
Yup. A textbox, which has special features. I plan on putting it on pages with buttons. My thought is as a developer, I would want to type something like this:
<ul class="list-inline" ng-controller="entryController">
<li><my-text-box data="enteredData" /></li>
<li><button class="btn btn-info" ng-click="enterClick();">Enter</button></li>
</ul>
Please note, I do not want buttons in my control. I also want the enteredData to be available on the scope associated with child controls. In other words, when enterClick is called, I want to be able to read the value via $scope.enteredData. In an attempt to create my-text-box, I've built the following directive:
myApp.directive('myTextBox', [function() {
return {
restrict:'E',
scope: {
entered: '='
},
templateUrl: '/templates/myTextBox.html'
};
}]);
myApp.controller('myTextBoxController', ['$scope', function($scope) {
$scope.doSomething = function($item) {
$scope.entered = $item.name;
// Need to somehow call to parent scope here.
};
}]);
myTextBox.html
<div ng-controller="myTextBoxController">
<input type="text" class="form-control" ng-model="query" placeholder="Please enter..." />
</div>
entryController.js
myApp.controller('entryController', ['$scope', function($scope) {
$scope.enteredData = '';
$scope.enterClick = function() {
alert($scope.enteredData);
};
});
Right now, I have two issues.
When enterClick in entryController is called, $scope.enteredData is empty.
When doSomething in myTextBoxController is called, I do not know how to communicate to entryController that something happened.
I feel like I've setup my directive correctly. I'm not sure what I'm doing wrong. Can someone please point me in the correct direction.

Three suggestions for you.
1) You really shouldn't create a directive with a template that references a controller defined elsewhere. It makes the directive impossible to test in isolation and is generally unclear. If you need to pass data into a directive from a parent scope use the isolate scope object on your directive to bind to that data (Note how the directive template doesn't have a controller) http://jsfiddle.net/p4ztunko/
myApp.directive('myTextBox', [function () {
return {
restrict: 'E',
scope: {
data: '='
},
template: '<input type="text" class="form-control" ng-model="data" placeholder="Please enter..." />'
};
}]);
myApp.controller('entryController', ['$scope', function ($scope) {
$scope.enteredData = 'Stuff';
$scope.enterClick = function () {
alert($scope.enteredData);
};
}]);
<div>
<ul class="list-inline" ng-controller="entryController">
<li>{{enteredData}}
<my-text-box data="enteredData" />
</li>
<li>
<button class="btn btn-info" ng-click="enterClick();">Enter</button>
</li>
</ul>
</div>
2) Don't obfuscate HTML when you don't need to. One of the goals of angular is to make the markup more readable, not replace standard elements with random custom elements. E.g. If you want to watch the value of the input and take action depending on what it is you could do that in the linking function (Note: still not referencing an external controller) http://jsfiddle.net/Lkz8c5jo/
myApp.directive('myTextBox', function () {
return {
restrict: 'A',
link: function(scope, element, attrs){
function doSomething (val) {
alert('you typed ' + val);
}
scope.$watch(attrs.ngModel, function (val) {
if(val == 'hello'){
doSomething(val);
}
});
}
};
});
myApp.controller('entryController', ['$scope', function ($scope) {
$scope.enteredData = 'Stuff';
$scope.enterClick = function (data) {
alert('You clicked ' + data);
};
}]);
<div>
<ul class="list-inline" ng-controller="entryController">
<li>{{enteredData}}
<input type="text" ng-model="enteredData" my-text-box />
</li>
<li>
<button class="btn btn-info" ng-click="enterClick(enteredData)">Enter</button>
</li>
</ul>
</div>
3) Pass data into controller functions from the UI instead of referencing the $scope object in the function like in ng-click="enterClick(enteredData)" It makes testing easier because you remove the $scope dependency from that method

$scope.enteredData is empty because you're not using the correct scope. The $scope in entryController is not the same $scope as in myTextBoxController. You need to specify one of these controllers on your directive, and then use that to reference the proper scope.
It seems like you should move the enterClick and corresponding button into your directive template. Then move the enter click into your text box controller and you will be able to reference $scope.enteredData.
You can notify a parent scope of a change by using $emit. (This is in reference to your comment "// Need to somehow call to parent scope here.")
Furthermore, you may have an issue of not using the proper variable. In myTextBox directive, you declare $scope.entered, yet you are effectively setting $scope.data equal to the value of enteredData in the html.

Related

Two way binding in custom directive with ng-repeat

I basically have a list of items that are stored as an array of objects. Some of these items are "children" of others. This is denoted by a "parentid" setting in each object. This only means that I want to display children as a nested list within the parent.
So, I start by iterating through the array and find one with no parent. When I find it, I call a directive that takes that ID and then again iterates through the main array and finds any item whose parentID is identical to the one in question and displays it. There can be multiple levels of children so that the directive is called recursively.
This works fine and displays all of the children, but I want to be able to select any one of these items and see that ID or object at the top level. This is not working. I pass a variable into each directive with two way binding but no parent is ever updated. I understand the primitive problem and I am passing an object but that is not working. I think that I need to do something with the repeats, but I am not sure what. I do not think transclusion is the issue.
In the demo below, I need to display the updated var3 variable whenever I click on an item.
Initial HTML
<div>{{var3}}</div>
<div>
<my-directive var1="item1"
var2="item2"
var3="item3">
</my-directive>
</div>
Directive
(function ()
{
'use strict';
angular
.module('app.core')
.directive('myDirective', myDirective);
function structureContent($templateRequest, $compile)
{ return {
restrict : 'E',
scope:{
var1:'=',
var2:'#',
var3:'='
},
controller : ["$scope", "$element", "$attrs",
function($scope, $element, $attrs) {
}
],
link : function(scope, element, attrs){
scope.$watch('worksheet',
function(){
$templateRequest("myTemplate.html").then(function(html){
var template = angular.element(html);
element.html(template);
$compile(template)(scope);
});
}, true
);
}
}
};
})();
Directive HTML
<div>
<div ng-click="var3=thisItem.itemid;">(Display item) </div>
// var3 is what I want to be able to pull out at the top level
</div>
<div ng-repeat="thisObj in myArray | orderBy:'order' track by thisObj.itemid"
ng-switch on="thisObj.type_id"
ng-if="thisObj.content.parentid==thisItem.itemid"
class="subSection" >
<div ng-switch-when="1">
<my-directive var1="{{var1}}"
var2="var2"
var3="var3">
</my-directive>
</div>
</div>

Trouble with executing Angular directive method on parent

I have a directive inside a directive, and need to call a parent method using the child directive. I'm having a bit of trouble passing the data around, and thought y'all might have an idea.
Here's the setup:
My parent directive is called screener-item. My child directive is called option-item. Inside of every screener-item, there might be n option-items, so they're dynamically added. (Essentially, think of this as dynamically building a dropdown: the user gives it a title, then a set of options available)
Here's how this is set up:
screener-item.directive.js
angular.module('recruitingApp')
.directive('screenerItem', function(Study, $compile) {
return {
templateUrl: 'app/new-study/screener-item/screener-item.html',
scope: {
study: '='
},
link: function(scope, el, attrs) {
var options = [];
scope.addOptionItem = function(item) {
options.push(item);
}
scope.saveScreenerItem = function() {
if (scope.item._id) {
var isEdit = true;
}
Study.addScreenerQuestion({id:scope.study._id},{
_id: scope.item._id,
text: scope.item.text,
type: scope.item.type
}, function(item){
scope.mode = 'show';
scope.item._id = item._id;
if (!isEdit) {
el.parent().append($compile('<screener-item study="newStudy.study"></screener-item')(scope.$parent));
}
});
}
}
}
});
screener-item.html
<div class="screener-item row" ng-hide="mode == 'show'">
<div class="col-md-8">
<input type="text" placeholder="Field (e.g., name, email)" ng-model="item.text">
</div>
<div class="col-md-3">
<select ng-model="item.type">
<option value="text">Text</option>
<option value="single_choice">Single Select</option>
<option value="multi_choice">Multi Select</option>
</select>
<div ng-show="item.type == 'single_choice' || fieldType == 'multi_choice'">
<h6>Possible answers:</h6>
<option-item item-options="options" add-option-item="addOptionItem(value)"><option-item>
</div>
</div>
<div class="col-md-1">
<button ng-click="saveScreenerItem()">Save</button>
</div>
</div>
<div class="screener-item-show row" ng-model="item" ng-show="mode == 'show'">
<div class="col-md-8">{{item.text}}</div>
<div class="col-md-3">({{item.type}})</div>
<div class="col-md-1">
<a ng-click="mode = 'add'">edit</a>
</div>
</div>
You'll notice option-item which is included there in them middle. That's the initial option offered to the user. This may be repeated, as the user needs it to be.
option.item.directive.js
angular.module('recruitingApp')
.directive('optionItem', function($compile) {
return {
templateUrl: 'app/new-study/screener-item/option-item.html',
scope: {
addOptionItem: '&'
},
link: function(scope, el, attrs) {
scope.mode = 'add';
scope.addItem = function(value) {
console.log("Value is ", value);
scope.addOptionItem({item:value});
scope.mode = 'show';
var newOptionItem = $compile('<option-item add-option-item="addOptionItem"></option-item')(scope);
el.parent().append(newOptionItem);
}
}
}
});
option-item.html
<div ng-show="mode == 'add'">
<input type="text" ng-model="value">
<button ng-click="addItem(value)">Save</button>
</div>
Here's what I want to happen: When the user enters a value in the option-item textbox and saves it, I want to call addItem(), a method on the option-item directive. That method, then, would call the parent method - addOptionItem(), passing along the value, which gets pushed into an array that's kept on the parent (this array keeps track of all the options added).
I can get it to execute the parent method, but for the life of me, I can't get it to pass the values - it comes up as undefined each time.
I'm trying to call the option-item method instead of going straight to the parent, so that I can do validation if needed, and so I can dynamically add another option-item underneath the current one, once an item is added.
I hope this makes sense, please let me know if this is horribly unclear.
Thanks a ton!
EDIT: Here's a jsFiddle of it: http://jsfiddle.net/y4uzbapz/1/
Note that when you add options, the logged out array of options on the parent is undefined.
Got this working. All the tutorials have this working by calling the parent method on ng-click, essentially bypassing the child controller. But, if you need to do validation before passing the value up to the parent, you need to call a method on the child directive, then invoke the parent directive's method within that call.
Turns out, you can access it just the same way that you can as if you were putting the expression inside of ng-click.
Here's a fiddle showing this working: http://jsfiddle.net/y4uzbapz/3/
Notice that the ng-click handler is actually on the child directive, which calls the parent directive's method. This lets me do some pre/post processing on that data, which I couldn't do if I'd invoked the parent directive directly from ng-click.
Anyway, case closed :)

Create new isolated scope programmatically

I am trying to create popup html to go into a leafletjs marker popup.
I have the following partial:
<div class="popup">
<div class="pull-right">
<a class="popup-info" ng-click="onInfoClicked()">
<i class="fa fa-info-circle"></i>
</a>
</div>
<div class="popup-title">
{{title}}
</div>
<div class="popup-subtitle">
{{subtitle}}
</div>
</div>
and the following directive:
app.directive('leafletPopup', function() {
return {
restrict: "A",
templateUrl: "app/partials/leaflet-popup.html",
scope: {
feature: '=',
popupInfo: '&'
},
controller: function ($scope) {
$scope.title = $scope.feature.properties.title;
$scope.subtitle = $scope.feature.properties.description;
$scope.onInfoClicked = function() {
$scope.popupInfo({feature: feature});
}
}
};
});
I have a controller that provides a function to generate the html for each marker that I am going to place on the map:
function html(feature) {
var el = angular.element('<div leaflet-popup="feature" popup-info="onPopupInfo(feature)"></div>');
var compiled = $compile(el);
var newScope = $scope.$new(true); // create new isolate scope
newScope.feature = feature; // inject feature into the scope
newScope.onPopupInfo = function(feature) { // inject function into scope
// do something with the click
showFeatureDetails(feature);
}
compiled(newScope);
return el[0];
}
Works perfectly. Great right?
I have read in a couple of places that its not recommended to create your own scope manually as you have to make sure you also destroy it manually.
Lets say I have a bunch of markers on my map, and each has a popup. Do I need to track all the new scopes I create in my controller and call destroy on them? When? Only if my marker gets removed from the map?
I could just skip angular and build the entire html element with jquery and attach the onclick to a function, but that is also not pretty. And why skip angular?
Seems overly complicated, which probably means I am doing this the hard way ;)

Call a function in a angular-controller from outside of the controller?

I have a lightbox-dierective and controller that looks like this:
directive('modalDialog', function() {
return {
restrict: 'E',
scope: {
show: '='
},
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
template: '<div class="ng-modal" ng-show="show"><div class="ng-modal-overlay" ng-click="hideModal()"></div><div class="ng-modal-dialog" ng-style="dialogStyle"><div class="ng-modal-dialog-content" ng-transclude><div class="ng-modal-close" ng-click="hideModal()">X</div></div></div></div>'
};
}).controller('Lightbox', function($scope) {
$scope.modalShown = false;
$scope.toggleModal = function() {
$scope.modalShown = !$scope.modalShown;
};
});
Here is the desierd html, what I need is to open the secon ligthbox from withing the first one:
<div ng-controller="Lightbox">
<span ng-mousedown='toggleModal()'>Open lightbox one</span>
<modal-dialog show='modalShown'>
<h2>One lightbox <span ng-mousedown='toggleModal()'>Open lightbox two</span></h2>
</modal-dialog>
</div>
<div ng-controller="Lightbox">
<span ng-mousedown='toggleModal()'>Open lightbox one</span>
<modal-dialog show='modalShown'>
<h2>another lightbox</h2>
</modal-dialog>
</div>
For most cases it works great! I use it in several occations throughout the site, with diffrent lightboxes and different content.
I have now come across a case, where I need to call one of the lightboxes from outside of the controller. Can this be achieved and in that case how do I reference the right lightbox?
I'd extend that setting to an object
var modalSet = {
shown: false,
toggle: function(){ modalSet.shown = !modalSet.shown }
}
Then put it on your main controller (the one with ngApp attribute) and have your entire scope modaleble.
Also, directives do have a controller option, but since only one modal is gonna show up at any given time, you might not want to re-create a controller for every new instance.
Upon re-reading your question: Where is it exactly -> "outside of the controller"?

AngularJS input with focus kills ng-repeat filter of list

Obviously this is caused by me being new to AngularJS, but I don't know what is the problem.
Basically, I have a list of items and an input control for filtering the list that is located in a pop out side drawer.
That works perfectly until I added a directive to set focus to that input control when it becomes visible. Then the focus works, but the filter stops working. No errors. Removing focus="{{open}}" from the markup makes the filter work.
The focus method was taken from this StackOverflow post:
How to set focus on input field?
Here is the code...
/* impersonate.html */
<section class="impersonate">
<div header></div>
<ul>
<li ng-repeat="item in items | filter:search">{{item.name}}</li>
</ul>
<div class="handle handle-right icon-search" tap="toggle()"></div>
<div class="drawer drawer-right"
ng-class="{expanded: open, collapsed: !open}">
Search<br />
<input class="SearchBox" ng-model="search.name"
focus="{{open}}" type="text">
</div>
</section>
// impersonateController.js
angular
.module('sales')
.controller(
'ImpersonateController',
[
'$scope',
function($scope) {
$scope.open = false;
$scope.toggle = function () {
$scope.open = !$scope.open;
}
}]
);
// app.js
angular
.module('myApp')
.directive('focus', function($timeout) {
return {
scope: { trigger: '#focus' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if(value === "true") {
console.log('trigger',value);
$timeout(function() {
element[0].focus();
});
}
});
}
};
})
Any assistance would be greatly appreciated!
Thanks!
Thad
The focus directive uses an isolated scope.
scope: { trigger: '#focus' },
So, by adding the directive to the input-tag, ng-model="search.name" no longer points to ImpersonateController but to this new isolated scope.
Instead try:
ng-model="$parent.search.name"
demo: http://jsbin.com/ogexem/3/
P.s.: next time, please try to post copyable code. I had to make quite a lot of assumptions of how all this should be wired up.

Resources