How to force recompile of directive with isolated scope? - angularjs

There are a few SO posts about refreshing a directive when a (model) value changes:
Angular Directive refresh on parameter change
AngularJS directive gets not updated if scope variable changes
The recommended approach is to watch a value on the scope in the linking function:
link: function(scope, element, attrs) {
scope.$watch("typeId",function(newValue,oldValue) {
// This gets called when data changes.
});
}
Given the following implementation of the recursive directive, <my-directive>:
angular.module('Myapp').directive("MyDirective", function(RecursionHelper) {
return {
restrict: "E",
scope: {
data: '=data'
},
templateUrl: 'view.html',
compile: function(tElement, tAttributes) {
return RecursionHelper.compile(tElement, tAttributes);
}
};
});
...and the RecursionHelper:
angular.module('Myapp').factory('RecursionHelper',
['$compile',
function($compile) {
var RecursionHelper = {
compile: function(tElement, tAttrs) {
var contents = tElement.contents().remove();
var compiledContents;
return {
post: function(scope, iElement, iAttrs) {
if (!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone) {
iElement.append(clone);
});
},
pre: function(scope, iElement, iAttrs) { }
}
}
}
return RecursionHelper;
}]);
I could add the listener to my linking function:
angular.module('Myapp').factory('RecursionHelper',
['$compile','MyService',
function($compile, MyService) {
var RecursionHelper = {
compile: function(tElement, tAttrs) {
var contents = tElement.contents().remove();
var compiledContents;
return {
post: function(scope, iElement, iAttrs) {
if (!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone) {
iElement.append(clone);
});
// The listener function.
scope.$watch(MyService.data,function(newValue,oldValue) {
// This gets called when data changes.
});
},
pre: function(scope, iElement, iAttrs) { }
}
}
}
return RecursionHelper;
}]);
I have added a Service, MyService, which contains data that may change and that I'm listening for. The first call to render the directive is started with main.html:
<my-directive data="data"></my-directive>
The directive's compile function is called and ultimately the template, view.html is rendered containing the recursive directive:
<span ng-repeat="item in data.items">
<my-directive data="item"></my-directive>
</span>
Since the <my-directive> data attribute has isolated scope, each nested directive will have its own 'sandboxed' scope.
Questions
My $watch function never gets called even though MyService.data is modified. Is this because the directive has isolated scope?
Assuming my $watch function is called, what is the actual implementation to trigger a recompilation? The SO posts just have comments of console.log statements, but I can't find anything on rendering the entire (root) directive again.

Related

Input does not reflect ngModel value

I am trying to do some custom validation based on a json object a user gives me.
However the input field visually does not show the value of the ngModel property. I added a plunkr to illustrate the problem.
'use strict';
angular.module('zendantennesApp')
.directive('validation', function ($compile, $parse) {
return {
scope: {
validation: '#',
ngModel: '#'
},
require: "?ngModel",
restrict: 'A',
compile: function(el, attrs) {
el.removeAttr('validation');
el.attr('ng-blur', 'evaluateExpression()');
el.attr('ng-focus', 'assignOriginalValue()');
var fn = $compile(el);
return function(scope, element, attrs, ngModel){
ngModel.$render = function(){
$(element).val(ngModel.$viewValue);
};
fn(scope);
}
},
controller: function($scope){
$scope.originalValue = $scope.ngModel;
$scope.validationObject = JSON.parse($scope.validation.replace(/'/g, '"'));
$scope.evaluateExpression = function(){
console.log($scope.validationObject);
};
$scope.assignOriginalValue = function(){
$scope.originalValue = $scope.ngModel;
console.log($scope.originalValue);
}
}
}
});
https://plnkr.co/edit/1qYxCiSZWHgVeN9CEpxw?p=preview
validation directive will have isolated scope and hence parent scope value will not be accessible unless you explicitly mention during compile. Replace fn(scope); by fn(scope.$parent);
Updated Plunker

I can pass a scope variable into a directive's link function, but not the compile function, angular

I'm using ng-repeat and I need to pass a scope variable into a directive's compile function. I know how to do it with the link function, but not the compile function.
My html looks like:
<div ng-repeat="item in chapter.main">
<block type="item.type"></block>
</div>
Let's say item.type="blah" no matter the item.
Then this link function works fine
app.directive('block', function() {
return {
restrict: 'E',
link: function(scope, element, attributes){
scope.$watch(attributes.type, function(value){
console.log(value); //will output "blah" which is correct
});
}
}
});
But I can't do the same with compile?
app.directive('block', function() {
return {
restrict: 'E',
compile: function(element, attrs, scope) {
scope.$watch(attrs.type, function(value){
console.log(value);
});
}
}
});
The error I get is "cannot read property $watch of undefined"..
This is how I'd like my directive to look like:
app.directive('block', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
element.append('<div ng-include="\'{{type}}-template.html\'"></div>');
//or element.append('<div ng-include="\'{' + attrs.type + '}-template.html\'"></div>');
//except the above won't interpret attr.type as a variable, just as the literal string 'item.type'
}
}
});
The compile function doesn't have scope as one it's parameter.
function compile(tElement, tAttrs, transclude) { ... }
NOTE: transclude is deprecated in the latest version of Angular.
Is there any reason you don't want to use link?
From the DOC
The compile function deals with transforming the template DOM. Since most directives do not do template transformation, it is not used often. The compile function takes the following arguments:
tElement - template element - The element where the directive has been declared. It is safe to do template transformation on the element and child elements only.
tAttrs - template attributes - Normalized list of attributes declared on this element shared between all directive compile functions.
transclude - [DEPRECATED!] A transclude linking function: function(scope, cloneLinkingFn)
UPDATE
To access the scope from inside compile function, you need to have either a preLink or postLink function. In your case, you need only the postLink function. So this ...
compile: function compile(tElement, tAttrs, transclude) {
return function postLink(scope, element, attrs) { ... }
},
PROPOSED SOLUTION Might not be exact but should help you on your way.
html
<div ng-app="myApp" ng-controller="app">
<block type="item.type"></block>
</div>
JS (Controller + Directive)
var myApp = angular.module('myApp', []);
myApp.controller('app', function ($scope, $http) {
$scope.item = {
type: 'someTmpl'
};
}).directive('block', ['$compile', function ($compile) {
return {
restrict: 'AE',
transclude: true,
scope: {
type: '='
},
compile: function (element, attrs) {
return function (scope, element, attrs) {
var tmpl;
tmpl = scope.type + '-template.html';
console.log(tmpl);
element.append('<div ng-include=' + tmpl + '></div>');
$compile(element.contents())(scope);
};
}
};
}]);

Why is a parent controller's $scope not accessible from a (child) directive?

From reading Scopes (Part 2 of the AngularJS - from beginner to expert in 7 steps series): A $scope can contain both data and functions available in a view. If AngularJS cannot find a function on a local $scope, the containing (parent) $scope will be checked for the property or method there.
Given my implementation of a directive's compile function (based on Angularjs: understanding a recursive directive):
compile: function(tElement, tAttrs) {
var contents = tElement.contents().remove();
console.log(contents);
var compiledContents;
// postLink function.
return {
post: function(scope, iElement, iAttrs) {
if (!compiledContents) {
// Get linking function.
compiledContents = $compile(contents);
}
// Link scope and the template together.
compiledContents(scope, function(clone) {
iElement.append(clone);
});
scope.myEvent = function() {
console.log("My Event handled!");
};
},
pre: function(scope, iElement, iAttrs) { }
}
}
In the code above, I have attached a function to the $scope of the instance element, and this is successfully called from the view. However I expected to be able to move the function definition from the instance element scope and into a parent controller's $scope:
angular.module('Myapp').controller('MyParentController', ['$scope',
function($scope) {
$scope.myEvent = function() {
console.log("My Event handled!");
};
}]);
However the parent controller's function is never called even though it is a parent of the directive for which I provided my own implementation of compile.
Updated to add code for the directive:
angular.module('Myapp').directive("my-directive", function(RecursionHelper) {
return {
restrict: "E",
scope: {
data: '=data'
},
templateUrl: 'view.html',
compile: function(tElement, tAttributes) {
return RecursionHelper.compile(tElement, tAttributes);
}
};
});
..and the RecursionHelper:
angular.module('Myapp').factory('RecursionHelper',
['$compile',
function($compile) {
var RecursionHelper = {
compile: function(tElement, tAttrs) {
var contents = tElement.contents().remove();
var compiledContents;
return {
post: function(scope, iElement, iAttrs) {
if (!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone) {
iElement.append(clone);
});
},
pre: function(scope, iElement, iAttrs) { }
}
}
}
return RecursionHelper;
}]);
change your scope to
scope: {
data: '=data'
myEvent: '=myEvent'
}
and then on your directive change this
angular.module('Myapp').directive("my-directive",
to
angular.module('Myapp').directive("myDirective",
then pass the function as in
<my-directive data="scope-data" my-event="scope-event-function()"></my-directive>
because your directive has an isolated scope, you can only access data in parent scope.
scope: {
data: '=data'
},

Angular Isolate Scope breaks down?

I have the following markup:
<div class="controller" ng-controller="mainController">
<input type="text" ng-model="value">
<div class="matches"
positions="{{client.positions | filter:value}}"
select="selectPosition(pos)">
<div class="match"
ng-repeat="match in matches"
ng-click="select({pos: match})"
ng-bind="match.name">
Then, inside my matches directive I have
app.directive('matches', function()
{
return {
scope: {
select: '&'
},
link: function(scope, element, attrs)
{
scope.matches = [];
attrs.$observe('positions', function(value)
{
scope.matches = angular.fromJson(value);
scope.$apply();
})
}
}
}
When I do this, I can console log scope.matches, and it does change with the value from my input. However, the last div .match doesn't render anything! If I remove scope: {...} and replace it with scope: true, then it does render the result, but I want to use the & evaluation to execute a function within my main controller.
What do i do?
Use scope.$watch instead, you can watch the attribute select whenever changes are made from that attribute.
app.directive('matches', function()
{
return {
scope: true,
link: function(scope, element, attrs)
{
scope.matches = [];
scope.$watch(attrs.select, function(value) {
scope.matches = angular.fromJson(value);
});
}
}
}
UPDATE: Likewise, if you define select itself as a scope attribute, you must use the = notation(use the & notation only, if you intend to use it as a callback in a template defined in the directive), and use scope.$watch(), not attr.$observe(). Since attr.$observe() is only used for interpolation changes {{}}, while $watch is used for the changes of the scope property itself.
app.directive('matches', function()
{
return {
scope: {select: '='},
link: function(scope, element, attrs)
{
scope.matches = [];
scope.$watch('select', function(value) {
scope.matches = angular.fromJson(value);
});
}
}
}
The AngularJS Documentation states:
$observe(key, fn);
Observes an interpolated attribute.
The observer function will be invoked once during the next $digest
following compilation. The observer is then invoked whenever the
interpolated value changes.
Not scope properties defined as such in your problem which is defining scope in the directive definition.
If you don't need the isolated scope, you could use $parse instead of the & evaluatation like this:
var selectFn = $parse(attrs.select);
scope.select = function (obj) {
selectFn(scope, obj);
};
Example Plunker: http://plnkr.co/edit/QZy6TQChAw5fEXYtw8wt?p=preview
But if you prefer the isolated scope, you have to transclude children elements and correctly assign the scope of your directive like this:
app.directive('matches', function($parse) {
return {
restrict: 'C',
scope: {
select: '&',
},
transclude: true,
link: function(scope, element, attrs, ctrl, transcludeFn) {
transcludeFn(scope, function (clone) {
element.append(clone);
});
scope.matches = [];
attrs.$observe('positions', function(value) {
scope.matches = angular.fromJson(value);
});
}
}
});
Example Plunker: http://plnkr.co/edit/9SPhTG08uUd440nBxGju?p=preview

When i require ngModel controller how do I access a property of the model controller

I am using ng-repeat and setting a model with it similar to the following
<div ng-repeat="thing in things" ng-model="thing" my-directive>
{{thing.name}}
</div>
then in my directive it looks something like this
.directive("myDirective, function () {
return {
require: 'ngModel',
link: function(scope, lElement, attrs, model) {
console.log(model.name);// this gives me 'NAN'
}
}
})
My question is how can I access the values in the model? I tried model.$modelValue.name but that did not work.
If you want to bind in a scoped value then you can use the '=' in an isolated. This will appear on the scope of your directive. To read the ng-model directive, you can use =ngModel:
.directive("myDirective", function () {
return {
scope: {
model: '=ngModel'
}
link: function(scope) {
console.log(scope.model.name); // will log "thing"
}
}
});
.directive("myDirective", function () {
return {
require: 'ngModel',
link: function(scope, lElement, attrs, model) {
console.log(attrs.ngModel); // will log "thing"
}
}
})
If your directive does not have isolated or child scope then you can do this:
.directive('someDirective', function() {
return {
require: ['^ngModel'],
link: function(scope, element, attrs, ctrls) {
var ngModelCtrl = ctrls[0];
var someVal;
// you have to implement $render method before you can get $viewValue
ngModelCtrl.$render = function() {
someVal = ngModelCtrl.$viewValue;
};
// and to change ngModel use $setViewValue
// if doing it in event handler then scope needs to be applied
element.on('click', function() {
var val = 'something';
scope.$apply(function() {
ngModelCtrl.$setViewValue(val);
});
});
}
}
});

Resources