Multiple instances of custom directive, confusion with ngModel - angularjs

I've created a custom directive to render a slider for a question (essentially wrapping jquery ui slider). The directive takes an ngModel and updates it when the user uses the slider, and there's a $watch attached to the parent model (the ngModel passed to the directive is only a part of a parent model). The directive has multiple instances on a page.
I've encountered an issue with the watch, as it seems as the watch always occurs on the last question on the page. So for example a page with 10 question, using the slider on question 1 - triggers the watch on the last question (question 10). I believe the issue has something to do with directives/isolated scope and/or the watch function, but I'm unable to solve it.
this.app.directive('questionslider', () => {
var onChangeEvent = (event, ui) => {
updateModel(ui.value);
};
var onSlideEvent = (event, ui) => {
updateUi(event, ui);
};
var updateUi = (event, ui) => {
$(ui.handle).find(".ff-handle-glyph > div").css("top", (ui.value) * - 10);
}
var updateModel = (newValue) => {
// find value in values list...
angular.forEach(isolatedScope.model.PossibleValues, function(value) {
if (parseInt(value.Name) === newValue) {
isolatedScope.$apply(function() {
isolatedScope.model.Value = value;
});
}
});
};
var isolatedScope: any;
return {
restrict: 'AE',
replace: true,
template: '<div></div>',
scope: {
model: '=ngModel',
},
link: function(scope, element, attrs, ctrl) {
isolatedScope = scope;
scope.$watch(ngModelCtrl, function() {
// use provided defaultValue if model is empty
var value = isolatedScope.model.Value === null ? isolatedScope.model.DefaultValue : isolatedScope.model.Value;
element.slider({
min: 0,
max: isolatedScope.model.PossibleValues.length,
value: value.Name,
change: onChangeEvent,
slide: onSlideEvent
});
}
}
};
};
Code to add watch in controller
this.$scope.questions.forEach(function(question) {
this.$scope.$watch(
function() { return question; },
function(newVal, oldVal) { this.updateQuestion(newVal, oldVal) },
true
);
});
UpdateQuestion function (right now just outputting current question)
function updateQuestion(newVal, oldVal) {
// prevent event on initial load
if (newVal === oldVal) {
return;
}
console.log(newVal);
}
The ng-repeat markup instantiating questionsliders
<div data-ng-repeat="question in Questions">
<h4>{{question.QuestionText}}</h4>
<p>{{question.RangeMinText}}</p>
<questionslider ng-model="question"></questionslider>
<p>{{question.RangeMaxText}}</p>
</div>
Question JSON would look like this
{
"DefaultValue": {
"Id": "5",
"Name": "5"
},
"Id": "1",
"IsAnswered": false,
"PossibleValues": [
{
"Id": "1",
"Name": "1"
},
{
"Id": "2",
"Name": "2"
},
{
"Id": "3",
"Name": "3"
},
{
"Id": "4",
"Name": "4"
},
{
"Id": "5",
"Name": "5"
},
{
"Id": "6",
"Name": "6"
},
{
"Id": "7",
"Name": "7"
},
{
"Id": "8",
"Name": "8"
},
{
"Id": "9",
"Name": "9"
},
{
"Id": "10",
"Name": "10"
}
],
"QuestionText": "hows it haning?",
"RangeMaxText": "not good",
"RangeMinText": "Very good",
"Type": 0,
"Value": null
}
],
"Title": "Question title",
"Type": 0
}
So issue is, no matter which question I update with the slider directive, it's always the last on page passed into updateQuestion.
UPDATE
I tried using $watchCollection, but nothing seems to fire the event.
this.$scope.$watchCollection(
'questions',
function (newVal, oldVal) {
// prevent event on initial load
if (newVal === oldVal) {
return;
}
for (var i = 0; i < newVal.length; i++) {
if (newVal[i] != oldVal[i]) {
this.$log.info("update : " + newVal.Id);
}
}
}
);
I also tried with
function() { return questions; }
as first expressions. Still no luck.
Maybe using individual controllers for each question is my only option, but it seems a bit of a workaround.
UPDATE
So i tried using individual controllers for each question, adding a watch per question in the controller, and the strange thing is that even this is reproducing same scenario. It's still the last question on the page passed into the watch function.
markup
<div data-ng-repeat="question in Questions" data-ng-controller="QuestionInstanceController">
<h4>{{question.QuestionText}}</h4>
<p>{{question.RangeMinText}}</p>
<questionslider ng-model="question"></questionslider>
<p>{{question.RangeMaxText}}</p>
</div>
Controller code
app.controller('QuestionInstanceController', function($scope) {
console.log($scope.question); // outputs correct question here!
$scope.$watch(
function() { return $scope.question; },
function(newValue, oldValue) {
console.log(newValue); // always outputs last question on page
},
true);
}
}
It must have something to do with my custom directive, am i somehow overwriting previous instances when having multiple instances on the page?

So i managed to find the solution myself. The issue was that i had a "var isolatedScope;" in the directive which was assigned on every run of the link(). I thought vars declared in the directive were isolated on each instance but infact they are overwritten on every implementation of the directive.
The solution therefore was to move the implementation of onChange directly to the init of the slider component, and thus avoiding the need of access to the scope variable later
this.app.directive('questionslider', () => {
var onChangeEvent = (event, ui) => {
};
var onSlideEvent = (event, ui) => {
updateUi(ui.value, ui.handle);
};
var updateUi = (value, element) => {
}
var onStartSlide = (event, ui) => {
}
var onEndSlide = (event, ui) => {
}
return {
restrict: 'AE',
require: 'ngModel',
replace: true,
templateUrl: 'templates/questionSlider.html',
scope: {
model: '=ngModel'
},
link: (scope: any, element, attrs, ngModelCtrl: ng.INgModelController) => {
scope.$watch(ngModelCtrl, () => {
// use provided defaultValue if model is empty
var value = scope.model.Value === null ? scope.model.DefaultValue : scope.model.Value;
var hasNoValue = scope.model.Value === null;
if (hasNoValue) {
element.find('.ui-slider-handle').addClass('dg-notset');
}
element.slider({
min: parseInt(scope.model.PossibleValues[0].Name),
max: scope.model.PossibleValues.length,
value: parseInt(value.Name),
slide: onSlideEvent,
start: onStartSlide,
stop: onEndSlide,
animate: true,
change: (event, ui) => {
// find value in values list...
angular.forEach(scope.model.PossibleValues, (val) => {
if (parseInt(val.Name) === ui.value) {
scope.$apply(() => {
scope.model.Value = val;
});
}
});
onChangeEvent(event, ui);
}
});
});
}
};
});

I expect that your $scope.$watch logic is throwing you off. The simplest way might be to put a watch on the entire array of questions using $watchCollection:
$scope.$watchCollection(questions, function(newValue, oldValue) {
for(index=0; index<newValue.length; index++) {
if (newValue[index] !== oldValue[index]) {
console.log("Question " + index + " updated to: " + newValue[index]);
}
}
});
Otherwise, you could probably create a separate controller for each item in your ng-repeat loop and have a watch there that deals with the change. I don't love this solution, either, as it's kinda long-winded. First, a new controller for dealing with the questions:
app.controller('QuestionCtrl', function($scope) {
$scope.$watch('question', function(newValue, oldValue) {
if (newVal === oldVal) {
return;
}
console.log(newVal);
}
});
With your view slightly modified to include a reference to the new QuestionCtrl:
<div data-ng-repeat="question in Questions" ng-controller='QuestionCtrl'>
<h4>{{question.QuestionText}}</h4>
<p>{{question.RangeMinText}}</p>
<questionslider ng-model="question"></questionslider>
<p>{{question.RangeMaxText}}</p>
</div>
This article gives more information about using controllers with ng-repeat.
I hope one of these helps you out.

Related

'click' not working AngularStrap $dropdown service

Using AngularStrap. Invoking the $dropdown service from the controller does show the dropdown, but the click on the items does not invoke the respective code.
Plunk to demonstrate this.
http://plnkr.co/edit/tNAX7liFSNh71XcOUecs
var dropdown = $dropdown(element, {
show: false,
trigger: "manual",
html: true
});
dropdown.$scope.content = [
{
"text": "<i class=\"fa fa-globe\"></i> Display an alert",
"click": "alert(\"Holy guacamole!\")"
},
{
"divider": true
},
{
"text": "Separated link",
"href": "#separatedLink"
}
];
element.on("contextmenu", function(event) {
event.preventDefault();
console.log("dropdown right click");
scope.$apply(function() {
scope.dropdown_show = true;
});
});
The alert function you are trying to call should exist in the scope.
try to add below in your controller, just above where you set the content.
dropdown.$scope.alert = function(str){
alert(str)
};

How do you use a recursive function within a directive in angularJS?

I'd like to create a ToDo app in AngularJS that uses nested ToDos. As part of this, I'd like the ability to indent or outdent a ToDo with a click (ultimately, it will react to a 'tab' or 'shift-tab' keypress). When indenting, the function should also indent any child ToDos. This is where I'm having trouble. I'm not sure how to implement a recursive function in a directive. If anyone has seen this done or could offer any help, i would appreciate it. I've created a working JSFiddle that indents a single ToDo but doesn't indent it's children. JS Fiddle is here https://jsfiddle.net/t1ba50k6/16/
Also, please offer any best practices on coding convention or to clean up the directive.
Thanks!
My HTML:
<ul id=Todos ng-app="app" ng-controller="todos">
<div ng-repeat='todo in model' ng-init="todoIndex = $index">
<todo-item content="todo"></todo-item>
</div>
My javascript:
var app = angular.module('app', []);
app.controller("todos", function ($scope) {
$scope.model = [{
"title": "Task item one",
"indentLevel": 1
}, {
"title": "Task item two",
"indentLevel": 2
}, {
"title": "Task item three",
"indentLevel": 2
}];
});
app.directive('todoItem', function ($compile) {
var getTemplate = function (content) {
var startStr = '';
var endStr = '';
if (content.indentLevel == 1) {
startStr = '<li class="todolist"><table><tr><td><div class="checkboxpadding"><img width="16" height="16" class="checkbox"></div></td><td><div ng-click="indent()">';
endStr = '</div></td></tr></table></li>';
return startStr + content.title + endStr;
} else if (content.indentLevel == 2) {
startStr = '<li class="todolist indent_2""><table><tr><td><div class="checkboxpadding"><img width="16" height="16" class="checkbox"></div></td><td><div ng-click="indent()">';
endStr = '</div></td></tr></table></li>';
return startStr + content.title + endStr;
}
};
var linker = function (scope, element, attrs) {
element.html(getTemplate(scope.content)).show();
$compile(element.contents())(scope);
scope.indent = function () {
var childElem = angular.element(element.children()[0]);
if (scope.content.indentLevel < 3) {
childElem.removeClass("indent_" + scope.content.indentLevel);
childElem.addClass("indent_" + (scope.content.indentLevel + 1));
scope.content.indentLevel++;
// update Database
// indent child nodes?
// for (var i=0; i < nodes; i++) { }
}
};
};
return {
restrict: "E",
link: linker,
scope: {
content: '='
}
};
});
Mapping your data to a nested structure would greatly simplify this.
Always use the same property names for the child arrays:
$scope.model = [{
"title": "Task item one",
"indentLevel": 1,
"children": [
{
"title": "Task item two",
"indentLevel": 2,
"children":[]
}, {
"title": "Task item three",
"indentLevel": 2,
"children":[]
}
]
}];
One solution is using $broadcast(name, args) and $on(name, listener) of scope.
when cliked fire an event:
scope.$broadcast('indent');
in child directives,
scope.$on('indent', scope.indent);

$scope$watch change one var if another changed

so i have to scope objects
$scope.hf_directory = data.features;
$scope.brylanty = data.features;
Actually they contain the same data, but i am trying to know how watch works so then i can use it in my project.
And i would like to watch hf_directory on which i use filter:search, so it would update scope.brylanty after typing something in input fiels ng-model="search"
i tried to do something like this but not making any changes
$scope.$watch('hf_directory', function (newValue, oldValue, $scope) {
if(newValue) {
$scope.brylanty = newValue;
}
});
Both scope objects are displayed by ng-repeat loop, on first i use filter:search on another nothing, i know i could just use another filter:search, but i want to learn how to use watch ;)
My objects are geojson data, they containt the same value, geojson look like below:
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "name": "SomeName"}, "geometry": { "type": "Point", "coordinates": [ 11.410585, 11.293361 ] } },
{ "type": "Feature", "properties": { "name": , "SecondName": { "type": "Point", "coordinates": [ 11.410585, 11.293361 ] } }, .......
]
}
After Your advices guys i tried this
$scope.search = {};
$scope.$watch('search', function (newVal) {
$scope.brylanty = newVal;
});
And this
$scope.$watch('search', function (newValue, oldValue, $scope) {
if (newValue) {
$scope.brylanty = newValue;
}
});
But without any good results, in both cases when i start typing something object brylanty is disappearing?
If you want to make changes upon typing something in the input ng-model="search" then ideally you should be watching the search variable. It should be
$scope.$watch('search', function (newValue, oldValue, $scope) {
if(newValue) {
$scope.brylanty = newValue;
}
});
This can also be written as (for 2 lines less)
$scope.$watch('search', function (newValue, oldValue, $scope) {
$scope.brylanty = (newValue) ? newValue : $scope.brylanty;
});
alternatively you could use ng-change in your input field and have
<input ng-model="search" ng-change="brylanty = (search) ? search : brylanty"/>
Watching hf_directory has no effect since typing in search doesn't affect it.
Edit: if you really want to watch hf_directory and it's an object/array then use
$scope.$watchCollection()
with the same arguments
UPDATE Added Demo
According to Docs
You can watch any variable by doing something like
$scope.$watch(function(){
return $scope.hf_directory; // or Directories.hf_directory if Directory is a factory/service
}, function(newVal, oldVal){
if(newVal != oldVal){
$scope.newestValue = newVal; // Do some cool UI
}
}, true); // true to check object equality (see below)
object equality is equivalent to angular.equal Source
I hope this helps.

$rootScope.$apply() ignores variable assignment

In my Service I have this code:
setInterval(function () {
$rootScope.$apply(function () {
cart.push({
"Id": 4,
"Name": "Some item",
"Price": 4
});
});
}, 3000);
Working example: http://jsfiddle.net/ko8edf32/7/
This works correctly: the cart change is pushed to the view.
However, when I assign a new value to cart, the change is NOT pushed to the view:
setInterval(function () {
$rootScope.$apply(function () {
var newcart = [{
"Id": 4,
"Name": "Some item " + Math.random(),
"Price": 4
}];
cart = newcart;
});
}, 3000);
example: http://jsfiddle.net/ko8edf32/8/
What is the reason of this?
What is the best/most elegant solution to solve this issue?
EDIT
This is the working solution I've built, based on the answers below:
jsfiddle.net/ko8edf32/11
I've changed your cart into more "angular" way with two-way databinding. I've added the second controller to show you how nice it works all together without getters/setters and generally with a bit of magic
http://plnkr.co/edit/U5pUlAPJTNd9V0baSjAu?p=preview
homeApp.factory("cartService", function($rootScope) {
var service = null
service = {
all: function() {
return service.cart;
},
add: function(item) {
service.total += item.Price
service.cart.push(item);
},
remove: function(item) {
service.total -= item.Price
service.cart.splice(service.cart.indexOf(item), 1);
},
cartUpdated: function(newValue) {
service.cart = newValue;
},
cart: [],
total: 0
}
return service;
});
You have to use objects on $scope.
$scope.model = { cart: [] };
Here is a working example: http://jsfiddle.net/56vkqygn/2/
Here is a explanation: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Angular ui-router's ui-sref created dynamically in a directive?

I am working on a line of business application that is using Angular to create a SPA around a Node.js api server. I decided on using ui-router cause of the state-machine and their intuitive way of embedding urls but I chanced upon a slight challenge when creating dynamic URLs within a directive.
I am using jQuery Datatables for my data grid as a directive but any action links generated using 'fnRender' don't seem to compile the 'ui-sref' to their respective 'href'links. The directive code is as follows:
app.directive('datatable', function ($http) {
return {
restrict: 'A',
link: function ($scope, $elem, attrs) {
var responsiveHelper;
var breakpointDefinition = {
tablet: 1024,
phone : 480
};
var options = {
bDeferRender: true,
sPaginationType: "full_numbers",
oLanguage: {
sEmptyTable: "No records returned",
sSearch: "<span>Search:</span> ",
sInfo: "Showing <span>_START_</span> to <span>_END_</span> of <span>_TOTAL_</span> entries",
sLengthMenu: "_MENU_ <span>entries per page</span>",
sProcessing: "Loading..."
},
sDom: "lfrtip",
oColVis: {
buttonText: "Change columns <i class='icon-angle-down'></i>"
},
oTableTools: {
sSwfPath: "js/plugins/datatable/swf/copy_csv_xls_pdf.swf"
},
bAutoWidth : false,
fnPreDrawCallback: function () {
if (!responsiveHelper) {
responsiveHelper = new ResponsiveDatatablesHelper($elem, breakpointDefinition);
}
},
fnRowCallback : function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
responsiveHelper.createExpandIcon(nRow);
},
fnDrawCallback : function (oSettings) {
responsiveHelper.respond();
}
};
if (typeof $scope.dtOptions !== 'undefined') {
angular.extend(options, $scope.dtOptions);
}
if (attrs['dtoptions'] === undefined) {
for (property in attrs) {
switch (property) {
case 'sajaxsource':
options['sAjaxSource'] = attrs[property];
break;
case 'sajaxdataprop':
options['sAjaxDataProp'] = attrs[property];
break;
}
}
} else {
angular.extend(options, $scope[attrs['dtoptions']]);
}
if (typeof options['sAjaxSource'] === 'undefined') {
throw "Ajax Source not defined! Use sajaxsource='/api/v1/*'";
}
if (typeof options['fnServerData'] === 'undefined') {
options['fnServerData'] = function (sSource, aoData, resultCb) {
$http.get(sSource, aoData).then(function (result) {
resultCb(result.data);
});
};
}
options.aoColumnDefs = [];
$elem.find('thead th').each(function() {
var colattr = angular.element(this).data();
if (colattr.mdata) {
if (colattr.mdata.indexOf("()") > 1) {
var fn = $scope[colattr.mdata.substring(0, colattr.mdata.length - 2)];
if (typeof fn === 'function') {
options.aoColumnDefs.push({
mData: fn,
sClass: colattr.sclass,
aTargets: [colattr.atargets]
});
} else {
throw "mData function does not exist in $scope.";
}
} else {
options.aoColumnDefs.push({
mData: colattr.mdata,
sClass: colattr.sclass,
bVisible: colattr.bvisible,
aTargets: [colattr.atargets]
});
}
} else {
if (colattr.fnrender.indexOf("()") > 1) {
var fn = $scope[colattr.fnrender.substring(0, colattr.fnrender.length - 2)];
if (typeof fn === 'function') {
options.aoColumnDefs.push({
fnRender: fn,
sClass: colattr.sclass,
aTargets: [colattr.atargets]
});
} else {
throw "fnRender function does not exist in $scope.";
}
} else {
options.aoColumnDefs.push({
fnRender: function (oObj) {
return "<a tooltip class='btn' title='View' ui-sref=\""+colattr.tag+".show({slug:\'"+oObj.aData._id+"\'})\"><center class=\"icon-search\"></center></a>";
},
sClass: colattr.sclass,
bVisible: colattr.bvisible,
aTargets: [colattr.atargets]
});
}
}
});
$elem.dataTable(options);
$(".dataTables_length select").wrap("<div class='input-mini'></div>").chosen({disable_search_threshold: 9999999 });
}
}
});
It runs with out complications and even generates the following anchor tag:
<a ui-sref="organisation.show({slug:'527a44c02aa9ce3a1c3fbc17'})"></a>
However, ui-router doesn't compile it to a respective state url. What could be the issue? Is there some configuration I may have missed?
Thanks
Are you using any other directives or expressions within your data table? I'm guessing those wouldn't work either, because it looks like Angular never gets the opportunity to compile any of the HTML you're generating.
This has nothing to do with uiSref and everything to do with writing directives correctly. In terms of best practices, this directive has way too much code. You should look at decomposing it into multiple nested directives and straight HTML. I'd suggest spending some time learning about transclusion and doing nested directives with directive controllers.
Leaving aside best practice, I just encountered and resolved this issue myself. Because DataTables is modifying the DOM outside of Angular's event loop, the ui-sref attributes don't get compiled. It's a simple fix: you need to call $compile on each row as it's created.
Here's my (much simpler) directive:
function datatable($compile) {
return {
restrict: "A",
link: (scope, elem, attrs) => {
// THE IMPORTANT BIT
scope.options.createdRow = function (row) {
$compile(row)(scope);
};
var api = elem.DataTable(scope.options);
var handleUpdates = function (newData) {
var data = newData || null;
if (data) {
api.clear();
api.rows.add(data).draw();
}
};
scope.$watch("options.data", handleUpdates, true);
},
scope: { options: "=" }
};
}

Resources