AngularJS directive attribute not rendering value when observed - javascript

I'm having trouble retrieving the value of an attribute passed in to a directive. My understanding of how directives work probably has something to do with this but it's my assumption that this is a scope related issue.
If you check the code below you'll see the attribute is being used as such:
display="contest.StyleBgImageMedia.filename"
This value of contest.StyleBgImageMedia.filename is a string and I've verified it exists by consoling it our from the controller. The problem is that when trying to access it within the directives link function I can't retrieve the value but only the attribute name.
This directive is used in the view like such:
<uploader class="pull-left" action="builder/uploadMediaFile" display="contest.StyleBgImageMedia.filename" data-file="style_bg_image_media_id"></uploader>
The full directive has been posted below. You'll see that I'm using $observe to render the value of the display attribute but this isn't working.
app.directive('uploader', function($rootScope) {
return {
restrict: 'E',
scope: {
action: '#',
display: '#display'
},
link: function(scope, elem, attrs) {
elem.find('.fake-uploader').click(function() {
elem.find('input[type="file"]').click();
});
scope.progress = 0;
attrs.$observe('display', function(value) {
if (value) {
scope.avatar = value;
}
});
scope.sendFile = function(el) {
var $form = jQuery(el).parents('form');
if (jQuery(el).val() === '') {
return false;
}
$form.attr('action', scope.action);
scope.$apply(function() {
scope.progress = 0;
});
$form.ajaxSubmit({
type: 'POST',
uploadProgress: function(event, position, total, percentComplete) {
scope.$apply(function() {
scope.progress = percentComplete;
});
},
error: function(event, statusText, responseText, form) {
$form.removeAttr('action');
},
success: function(responseText, statusText, xhr, form) {
var ar = jQuery(el).val().split('\\'),
filename = ar[ar.length-1];
$form.removeAttr('action');
scope.$apply(function() {
scope.avatar = filename;
});
var response = jQuery.parseJSON(responseText);
$rootScope.$broadcast('file-uploaded', {
'model': attrs.file,
'file': response.message
});
}
});
};
},
replace: false,
templateUrl: 'builder/views/partials/upload.php'
};
});

$observe doesn't work unless the attribute value contains interpolation.
So, you can change the attribute to be:
<uploader display="{{contest.StyleBgImageMedia.filename}}" ...>
Alternatively, you can use watch: scope.$watch('display', ...) with this isolated scope binding:
display: '='

Related

change directive when scope variable changes

I am using http request to get data from json file which I than use in controller.
app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) {
//gets data from service
loaderService.getLoadedHtml().then(function (result) {
$scope.fields = result.data;
});
}]);
I need to update directive when this $scope.fields change as
app.directive('dform', function () {
return {
scope: {
action: '#',
method: '#',
html: '='
},
link: function (scope, elm, attrs) {
var config = {
"html": scope.fields
};
scope.$watch('fields', function (val) {
elm.dform(config);
});
//console.log(config);
//elm.dform(config);
}
};
})
and here is how I am using this directive
<div html="fields" dform></div>
But in my case when $scope.fields changes, i get scope as undefined in my directive $watch function.
Question:
How can I get the updated value for scope.fields in scope.$watch function?
You need to give the directive access to fields by adding a binding for it:
scope: {
action: '#',
method: '#',
html: '=',
fields: '='
}
And HTML:
<dform fields="fields" ...
The value might be undefined the first time, then you don't want to call dform:
scope.$watch('fields', function(newValue, oldValue) {
if (newValue === oldValue) return;
var config = {
"html": newValue
};
elm.dform(config);
});
Update
With this HTML:
<div html="fields" dform></div>
You just need to watch html instead, no need for $parent or adding fields as a binding:
scope.$watch('html', ...
Usually for directives that should be as transparent as possible, no new scope is supposed be used. Having a new scope also prevents other directives from requesting a new scope on the same element.
If only one of the attributes is supposed to be dynamic, it is as simple as
scope: false,
link: function (scope, elm, attrs) {
scope.$watch(function () { return scope[attrs.html] }, function (val) {
if (val === undefined) return;
var config = {
action: attrs.action,
method: attrs.method,
html: val
};
elm.dform(config);
});
}
Alternatively, bindToController can be used in more modern, future-proof fashion (depending on what happens with html, $scope.$watch can be further upgraded to self.$onChanges hook).
scope: true,
bindToController: {
action: '#',
method: '#',
html: '='
},
controller: function ($scope, $element) {
var self = this;
$scope.$watch(function () { return self.html }, function (val) {
if (val === undefined) return;
var config = {
action: attrs.action,
method: attrs.method,
html: val
};
$element.dform(config);
});
}
Considering that html="fields", the code above will watch for fields scope property.
use $parent.fields instead of fields

Call function in Directive when Parent Scope Variable Changes

I need to call a function in my directive when the value of variable in the parent controller changes. I tried adding a watch (I'm obviously doing it wrong) because nothing happens when the value changes. Here is the directive:
angular.module('ssq.shared').directive('checkboxPicklist', function() {
return {
restrict: 'E',
templateUrl: '/Scripts/app/Shared/directives/checkboxPicklist.html',
replace: true,
scope: {
itemId: '=',
list: '=',
nameProp: '=',
title: '#',
searchPlaceholder: '#',
callbackFn: '&',
callMore: '&',
clear: '='
},
link: function (scope, element, attrs) {
scope.query = '';
var parent = scope.$parent;
var clear = parent.clear;
scope.$watch(clear, function () {
if (clear == true) {
this.clearAll();
}
})
var child = element.find('.dropdown-menu');
child.on({
'click': function (e) {
e.stopPropagation();
}
});
var selectedItemFn = function (item) {
return item.selected;
};
scope.getSelectedCount = function () {
return _.filter(scope.list, selectedItemFn).length;
};
scope.loadMore = function () {
scope.callMore();
};
scope.allSelected = function(list) {
var newValue = !scope.allNeedsMet(list);
_.each(list, function(item) {
item.selected = newValue;
scope.callbackFn({ object: item });
});
};
scope.allNeedsMet = function(list) {
var needsMet = _.reduce(list, function(memo, item) {
return memo + (item.selected ? 1 : 0);
}, 0);
if (!list) {
return (needsMet === 0);
}
return (needsMet === list.length);
};
function clearAll() {
_.each(list, function (item) {
item.selected = false;
})
}
}
};
});
Here is where I am trying to watch the variable:
var parent = scope.$parent;
var clear = parent.clear;
scope.$watch(clear, function () {
if (clear == true) {
this.clearAll();
}
})
Here is the function in my parent controller that changes the value of "clear"
$scope.clearFilters = function (clear) {
$scope.clear = true;
$scope.form.selected.services = [];
$scope.form.picked.areas = [];
$scope.form.certified.verifications = [];
$scope.form.subscribed.subscriptions = [];
$scope.form.OperatorBusinessUnitID = null;
$scope.form.OperatorBusinessUnitID = null;
};
I tried setting an attribute called "clearFilter" and assigning the variable to it, but the watch still doesn't trigger:
scope.$watch(attrs.clearFilter, function (value) {
if (value == true) {
this.clearAll();
}
});
<checkbox-picklist data-item-id="'servicesPicklist'"
data-search-placeholder="Search Services"
data-list="services"
data-title="Service(s)"
data-name-prop="'vchDescription'"
data-callback-fn="addService(object)"
call-more="loadMoreServices()"
clear-filter="clear">
</checkbox-picklist>
I'm not really sure if I am calling the function correctly. scope.$parent above does get the initial value of the variable from the parent scope, but once it changes, it never updates.
EDIT:What I have discovered is the normal scope.$watch('clear', function...) is not working it seems because the directive is in "ssq.shared" module which is injected in my my Main Module "myModule" (see below), so even though the page the directive is on uses my 'GeneralSearchCtrl', I cannot get the watch to work on the variable located in 'GeneralSearchCtrl'. If I use scope.$parent.clear I can see the value of the variable, but I cannot seem to set a watch on it.
My module injection code:
var app = angular.module('myModule', ['ui.bootstrap', 'checklist-model', 'ssq.shared', 'ngAnimate', 'ngTouch', 'ui.grid', 'ui.grid.pagination', 'ui.grid.selection', 'ui.grid.exporter', 'ui.grid.autoResize', 'ui.router', 'cgBusy', 'ui.mask', 'ngFileUpload', 'ngSanitize']);
The page where the directive lives uses:
<div ng-app="myModule" ng-controller="GeneralSearchCtrl">
I am unable to get a watch on the variable located in GeneralSearchCtrl.
Any assistance is greatly appreciated!!!!
Add a watch for the $scope value and call the function,
scope.$watch('clear', function(newValue, oldValue) {
if (newValue) {
this.clearAll();
}
});
scope.$watch(clear, function () {
if (clear == true) {
this.clearAll();
}
})
This.clearAll() doesn't exist in the scope of your $watch function. Simply calling clearAll() should work better.
The signature of the watch function is not correct.
scope.$watch('clear', function (new, old) {}
As it turns out, the problem was that the directive had scope:{...} in its definition which stopped the "normal" scope.$watch('clear', function...) from working. I had to add clear: '=' to the scope list like so:
replace: true,
scope: {
itemId: '=',
list: '=',
nameProp: '=',
title: '#',
searchPlaceholder: '#',
callbackFn: '&',
callMore: '&',
clear: '='
},
Then clear="clear" to the directive like so:
<checkbox-picklist data-item-id="'servicesPicklist'"
data-search-placeholder="Search Services"
data-list="services"
data-title="Service(s)"
data-name-prop="'vchDescription'"
data-callback-fn="addService(object)"
call-more="loadMoreServices()"
clear="clear">
</checkbox-picklist>
Then in the directive I had to add the watch like this for it work:
scope.$watch('$parent.clear', function (newValue, oldValue) {
if (newValue == true) {
clearAll();
alert('it works!');
}
})
I really hope this helps someone else as this was difficult for me to figure out. Happy coding!

ui-tinymce directive used into custom directive template : ngModel not updated

I currently have an issue when I call ui-tinymce directive in a custom directive. The custom directive is used to load dynamically links from backend for tinymce advlink plugin (+ load tinymce options object associated with a key passed as an attribute to the directive).
Here is my controller :
module.controller('Ctrl', function ($scope) {
$scope.test = {
val: "gfsgfdgh"
};
});
Here is how I call the directive in HTML:
<tinymce-custom type="minimal" ng-model="test.val"></tinymce-custom>`
And here is my directive :
module.directive('tinymceCustom', function($location, TinyService, Module, GenerateurPage) {
return {
restrict: 'E',
replace: true,
require:"ngModel",
scope: {
ngModel: '='
},
link: function(scope, element, attrs, ngModel){
scope.loaded = {
modules: false,
pages: false,
tinymce: false
};
scope.tinyOptions = {};
var link_list = [];
var modules = [];
var pages = [];
Module.findByOrganisme({}, function (data) {
data.forEach(function(module) {
modules.push({title: module.libelle, value: "/modules/"+module.id});
});
link_list.push({title: "Modules", menu: modules});
scope.loaded.modules = true;
initTiny();
});
GenerateurPage.findByOrganisme({}, function(data) {
data.forEach(function(page) {
pages.push({title: page.titre, value: "/#/generateurPage/afficherPage?id=/"+page.id});
});
link_list.push({title: "Pages", menu: pages});
scope.loaded.pages = true;
initTiny();
});
function initTiny() {
if (!scope.loaded.modules || !scope.loaded.pages) {
return false;
}
scope.tinyOptions = TinyService.options(attrs.type);
console.log(scope);
scope.tinyOptions.link_list = link_list;
scope.loaded.tinymce = true;
}
},
template: '<div ng-if="loaded.tinymce"><textarea ui-tinymce="tinyOptions" ng-model="ngModel"></textarea></div>'
};
});
The problem is that the model passed to ui-tinymce directive is not updated when changing the text with the editor, and the text in the editor is not updated when the model from the controller is changed... BUT, the initial ngModel value is passed to ui-tinymce directive, so I think that is the data binding that is broken. Tried to watch it with $watch but nothing happens.
I can't figure how to fix it so I'm now looking for some help...
Thx
Finaly fixed it changing the approach :
<textarea tinymce-custom="minimal" ng-model="myVar"></textarea >
The final directive :
module.directive('tinymceCustom', function($location, $compile, $q, TinyService, Module, GenerateurPage) {
return {
restrict: 'A',
priority:999,
terminal:true, // prevent lower priority directives to compile after it
scope: true,
require: ['?ngModel'],
link: function(scope, el, attrs) {
// default is basic template
var type = attrs.tinymceCustom ? attrs.tinymceCustom : 'basic';
function loadTinyOptions(name) {
var loaded = {
modules: false,
pages: false,
tinymce: false
};
var link_list = [];
var deferred = $q.defer();
var initTiny = function() {
if (!loaded.modules || !loaded.pages) {
return false;
}
var tinyOptions = TinyService.options(name);
tinyOptions.link_list = link_list;
deferred.resolve(tinyOptions);
};
Module.findByOrganisme({}, function (data) {
var modules = [];
data.forEach(function(module) {
modules.push({title: module.libelle, value: "/modules/"+module.id});
});
link_list.push({title: "Modules", menu: modules});
loaded.modules = true;
initTiny();
});
GenerateurPage.findByOrganisme({}, function(data) {
var pages = [];
data.forEach(function(page) {
pages.push({title: page.titre, value: "/#/generateurPage/afficherPage?id=/"+page.id});
});
link_list.push({title: "Pages", menu: pages});
loaded.pages = true;
initTiny();
});
return deferred.promise;
}
loadTinyOptions(type).then(function(data) {
scope._tinyOptions = data;
el.removeAttr('tinymce-custom'); // necessary to avoid infinite compile loop
el.attr('ui-tinymce', '{{_tinyOptions}}');
$compile(el)(scope);
});
}
};
Hope this can help.

$scope.$watch doesn't fire when I update from a directive

I have the following code snippets:
HTML:
<div data-filedrop data-ng-model="file"></div>
Controller:
$scope.$watch('file', function(newVal) {
if (newVal) {
alert("File",newVal);
}, false);
}
Directive:
angular.module('app').directive('filedrop', function () {
return {
restrict: 'A',
templateUrl: './directives/filedrop.html',
replace: true,
scope: {
ngModel: '=ngModel'
},
link: function (scope, element) {
var dropzone = element[0];
dropzone.ondragover = function () {
this.className = 'hover';
return false;
};
dropzone.ondragend = function () {
this.className = '';
return false;
};
dropzone.ondrop = function (event) {
event.preventDefault();
this.className = '';
scope.$apply(function () {
scope.ngModel = event.dataTransfer.files[0];
});
return false;
};
}
};
});
The $watch function is never triggered when I update the $scope.
Any Ideas?? Might be an isolated scope issue? It used to work until yesterday... when I had to redo
bower install && npm install
I can confirm:
dropzone.ondrop is fired
event.dataTransfer.files[0] does contain the file being dropped
because of the bower install I also tried angular 2.1.14, 2.1.15 and 2.1.16 (current) but none are working
Thanks!
Sander
ngModel is a controller/provider, it's not a scope. It's not identical to using a scope like in a controller in any way whatsoever. You have to use ngModel.$setViewValue('some value') to manipulate the value. You also have to add the ngModel like this:
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
// do some stuff
ngModel.$setViewValue(element.html()); // example
}
I found a good tutorial which describes this perfectly: http://suhairhassan.com/2013/05/01/getting-started-with-angularjs-directive.html#.U1jme-aSzQ4
Another option would of course be to just pass a scope variable like this:
Directive:
scope: {
'someAttribute': '='
},
link: function(scope, element) {
dropzone.ondrop = function(event) {
scope.$apply(function() {
scope.someAttribute = event.dataTransfer.files[0];
});
}
}
Controller View:
<div filedrop some-attribute="mymodel"></div>
Controller:
$scope.$watch('mymodel', function(newVal) {
// yeah
});
It seems that you are not modifying the value of scope.ngModel. Instead you are overwriting variable scope.ngModel so that it points to the different object, namely: event.dataTransfer.files[0]

Accessing scope within directive

I have a controller which is charge of getting event json data and if there is data, update the dom with data, else update dom with error message:
//Controller.js
myApp.controller('EventsCtrl', ['$scope','API', function ($scope, api) {
var events = api.getEvents(); //events: {data: [], error: {message: 'Some message'}}
}]);
//Directives.js
myApp.directive('notification', function () {
return {
restrict: 'A',
link: notificationLink
};
});
/**
* Creates notification with given message
*/
var notificationLink = function($scope, element, attrs) {
$scope.$watch('notification', function(message) {
element.children('#message').text(message);
element.slideDown('slow');
element.children('.close').bind('click', function(e) {
e.preventDefault();
element.slideUp('slow', function () {
element.children('#message').empty();
});
});
});
};
//Services.js
...
$http.get(rest.getEventsUrl()).success(function (data) {
// Do something with data
}).error(function (data) {
$window.notification = data;
});
Issue is that the element changes are triggered but $window.notification has nothing in it.
Edit: Attempted to try with $watch.
Edit: After moving both sets of html to one controller, the DOM manipulation works with $watch(). Thanks to both you of you for your help!
Try setting the result of your http request to a scope variable in your controller. Then watch that variable in your directive.
myApp.controller('EventsCtrl', ['$scope', 'API',
function ($scope, api) {
$scope.events = api.getEvents(); //events: {data: [], error: {message: 'Some message'}}
}
]);
//Directives.js
myApp.directive('notification', function () {
return {
restrict: 'A',
link: notificationLink
};
});
var notificationLink = function (scope, element, attrs) {
scope.$watch('events', function (newValue, oldValue) {
if (newValue !== oldValue) {
if (scope.events.data.length) {
//Display Data
} else {
//Display Error
}
}
});
};

Categories

Resources