Directive not working with ng-if - angularjs

I have the following directive that works correctly unless i use a ng-if on the containing element as well. What I am trying to do is simply set a dynamic property on the scope with an associated function. The scope does not contain the property (undefined).
any help would be great!
app.directive('stRefresh', function () {
return {
require: '^stTable',
link: function (scope, ele, attr, ctrl) {
if (attr.stRefresh) {
var name = attr.stRefresh;
scope[name] = scope[name] || {};
scope[name].refresh = function () {
return ctrl.search();
};
}
}
}
});

It would be helpful to know what doesn't work, but I suspect that you have been bitten by the problem of nested scopes.
The ng-if directive creates a child scope. When you modify the scope in your directive:
scope[name] = scope[name] || {};
You are modifying the child scope. Due to prototypal inheritance, this does not modify the scope of the parent. Therefore, if you are expecting to see a change in the parent scope, you won't see it.
To fix it, you need to add a dot to the scope reference. Something like this:
scope.data[name] = scope.data[name] || {};
scope.data[name].refresh = function () {
return ctrl.search();
};
The scope.data property needs to be a reference to an object. Since you are not modifying the reference, you can modify the properties of that object from both parent and child scopes.

Related

AngularJS directive doesn't update scope value even with apply

I'm usin a directive to show a div on the screen only when the screen size is smaller than 600px. The problem is, the scope value isn't being updated, even using $apply() inside the directive.
This is the code:
function showBlock($window,$timeout) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
scope.isBlock = false;
checkScreen();
function checkScreen() {
var wid = $window.innerWidth;
if (wid <= 600) {
if(!scope.isBlock) {
$timeout(function() {
scope.isBlock = true;
scope.$apply();
}, 100);
};
} else if (wid > 600) {
if(scope.isBlock) {
$timeout(function() {
scope.isBlock = false;
scope.$apply();
}, 100);
};
};
};
angular.element($window).bind('resize', function(){
checkScreen();
});
}
};
}
html:
<div ng-if="isBlock" show-block>
//..conent to show
</div>
<div ng-if="!isBlock" show-block>
//..other conent to show
</div>
Note: If I don't use $timeout I'll get the error
$digest already in progress
I used console logs inside to check if it's updating the value, and inside the directive everything works fine. But the changes doesn't go to the view. The block doesn't show.
You should use do rule in such cases to get the advantage of Prototypal Inheritance of AngularJS.
Basically you need to create a object, that will will have various property. Like in your case you could have $scope.model = {} and then place isBlock property inside it. So that when you are inside your directive, you will get access to parent scope. The reason behind it is, you are having scope: true, which says that the which has been created in directive is prototypically inherited from parent scope. That means all the reference type objects are available in your child scope.
Markup
<div ng-if="model.isBlock" show-block>
//..conent to show
</div>
<div ng-if="!model.isBlock" show-block>
//..other conent to show
</div>
Controller
app.controller('myCtrl', function($scope){
//your controller code here
//here you can have object defined here so that it can have properties in it
//and child scope will get access to it.
$scope.model = {}; //this is must to use dot rule,
//instead of toggle property here you could do it from directive too
$scope.isBlock = false; //just for demonstration purpose
});
and then inside your directive you should use scope.model.isBlock instead of scope.isBlock
Update
As you are using controllerAs pattern inside your code, you need to use scope.ag.model.isBlock. which will provide you an access to get that scope variable value inside your directive.
Basically you can get the parent controller value(used controllerAs pattern) make available controller value inside the child one. You can find object with your controller alias inside the $scope. Like here you have created ag as controller alias, so you need to do scope.ag.model to get the model value inside directive link function.
NOTE
You don't need to use $apply with $timeout, which may throw an error $apply in progress, so $timeout will run digest for you, you don't need to worry about to run digest.
Demo Here
I suspect it has something to do with the fact that the show-block directive wouldn't be fired if ng-if="isBlock" is never true, so it would never register the resize event.
In my experience linear code never works well with dynamic DOM properties such as window sizing. With code that is looking for screens size you need to put that in some sort of event / DOM observer e.g. in angular I'd use a $watch to observe the the dimensions. So to fix this you need to place you code in a $watch e.g below. I have not tested this code, just directional. You can watch $window.innerWidth or you can watch $element e.g. body depending on your objective. I say this as screens will be all over the place but if you control a DOM element, such as, body you have better control. also I've not use $timeout for brevity sake.
// watch window width
showBlock.$inject = ['$window'];
function bodyOverflow($window) {
var isBlock = false;
return {
restrict: 'EA',
link: function ($scope, element, attrs) {
$scope.$watch($window.innerWidth, function (newWidth, oldWidth) {
if (newWidth !== oldWidth) {
return isBlock = newWidth <= 600;
}
})
}
};
}
// OR watch element width
showBlock.$inject = [];
function bodyOverflow() {
var isBlock = false;
return {
restrict: 'EA',
link: function ($scope, element, attrs) {
$scope.$watch($element, function (new, old) {
if (newWidth) {
return isBlock = newWidth[0].offsetWidth <= 600;
}
})
}
};
}

Custom range angular directive with events

I'd like to create an range directive to repeat the included html x times.
Like this:
...
.directive('raichuRange', function () {
return{
scope:{
range: '=raichuRange'
},
transclude: 'element',
link : function(scope, element, attrs, ctrl, transcludeFn){
var parent = element.parent();
for(var i = 1;i<= scope.range;++i){
var childScope = scope.$new();
childScope.$index = i;
transcludeFn(childScope, function (clone) {
parent.append(clone);
})
}
}
}
})
The problem with this is: any ng-click directives within don't respond anymore.
Why doesn't this work? https://jsfiddle.net/pq1wkp90/
Because the directive uses an isolate scope, the parent functions are not inherited by the directive scope or their children.
To access the functions on the parent scope of the directive use:
ng-click="$parent.$parent.test($index)"
Use one $parent to access the isolate scope from the transcluded element. The second $parent to access the parent of the isolate scope.
For more information on directive scopes, AngularJS $compile API Reference -- scope.
PS. Also change $scope.$index = $index + 1; to $scope.$index = $scope.$index + 1;

Find closest controller scope

Is there a way to find the closest parent scope inside a directive that is a controller scope?
Use case.
The important part is at line 212 is the js file.
The template I render from the directive has scope expressions passed in the directive attribute and I need to link them to the controller scope.
Because the directive has an isolated scope, I link it to scope.$parent because in this case the parent is the controller.
But this might not always be the case, so how can I find the closest parent controller scope.
Can I loop trough the scope checking if it's a controller scope?
var template = angular.element(html);
var linkFn = $compile(template);
var child = linkFn(scope.$parent); //HERE IS THE PROBLEM
$(element).append(child);
You may try to use jqLite/jQuery methods from within your directive to traverse DOM tree up and locate the required parent (element.parent(), etc). Then you can get the scope object related to this parent by calling scope() method on it, which you should be able to pass as an argument to your compilation function.
It's not the cleanest approach, but you can always pass in an object to the directive's scope.
angular.app('myApp', [])
.controller('myCtrl', [function() {
var self = this;
self.directiveConfig = {
method1: function() { /* do something cool */ },
method2: function() { /* do something cool */ }
};
}])
.directive('myElem', [function() {
var myElem = {
restrict: 'AE',
controller: function() { /* some custom controller */ },
link: function(scope, element, attributes, ctrl) {
/**
* scope.config will now be tied to self.directiveConfig
* as defined in the controller above
*/
},
scope: {
config: '='
}
};
});
Then, assuming your controllerAs is set to ctrl, you could do.
<my-elem config="ctrl.directiveConfig"></my-elem>
A better solution would be to put any functions you need to use like that inside a service that can be reused.
See there are many ways . One of the way could be , you could check for an variable that is defined on that controller scope like this
if(angular.isDefined(scope.$parent.variableName))
{
// controller is defined
}
else
{
// controller is not defined
}
If this is defined then it is your controller , otherwise something else. Second way would be to check parent scope of the parent like this
if(angular.isDefined(scope.$parent.$parent)) {
//controller is defined
}
else
{
//controller is not defined
}
As every controller will have a parent as $rootScope or $scope of some other controller . That means if it is not a controller then this would result in undefined and will go else condition.
requiring ngController seems to be the best solution.
.directive("mobilitTree", function() {
return {
...
require: "ngController",
...
link: function(scope, element, attrs, ngCtrl) {
...
}
};
})
.controller("AppController", function($scope, ...) {
//Only variable applied on this are public
this.controllerOnSort = function(...) { ... };
});

AngularJS: Parent scope is not updated in directive (with isolated scope) two way binding

I have a directive with isolated scope with a value with two way binding to the parent scope. I am calling a method that changes the value in the parent scope, but the change is not applied in my directive.(two way binding is not triggered). This question is very similar:
AngularJS: Parent scope not updated in directive (with isolated scope) two way binding
but I am not changing the value from the directive, but changing it only in the parent scope. I read the solution and in point five it is said:
The watch() created by the isolated scope checks whether it's value for the bi-directional binding is in sync with the parent's value. If it isn't the parent's value is copied to the isolated scope.
Which means that when my parent value is changed to 2, a watch is triggered. It checks whether parent value and directive value are the same - and if not it copies to directive value. Ok but my directive value is still 1 ... What am I missing ?
html :
<div data-ng-app="testApp">
<div data-ng-controller="testCtrl">
<strong>{{myValue}}</strong>
<span data-test-directive data-parent-item="myValue"
data-parent-update="update()"></span>
</div>
</div>
js:
var testApp = angular.module('testApp', []);
testApp.directive('testDirective', function ($timeout) {
return {
scope: {
key: '=parentItem',
parentUpdate: '&'
},
replace: true,
template:
'<button data-ng-click="lock()">Lock</button>' +
'</div>',
controller: function ($scope, $element, $attrs) {
$scope.lock = function () {
console.log('directive :', $scope.key);
$scope.parentUpdate();
//$timeout($scope.parentUpdate); // would work.
// expecting the value to be 2, but it is 1
console.log('directive :', $scope.key);
};
}
};
});
testApp.controller('testCtrl', function ($scope) {
$scope.myValue = '1';
$scope.update = function () {
// Expecting local variable k, or $scope.pkey to have been
// updated by calls in the directive's scope.
console.log('CTRL:', $scope.myValue);
$scope.myValue = "2";
console.log('CTRL:', $scope.myValue);
};
});
Fiddle
Use $scope.$apply() after changing the $scope.myValue in your controller like:
testApp.controller('testCtrl', function ($scope) {
$scope.myValue = '1';
$scope.update = function () {
// Expecting local variable k, or $scope.pkey to have been
// updated by calls in the directive's scope.
console.log('CTRL:', $scope.myValue);
$scope.myValue = "2";
$scope.$apply();
console.log('CTRL:', $scope.myValue);
};
});
The answer Use $scope.$apply() is completely incorrect.
The only way that I have seen to update the scope in your directive is like this:
angular.module('app')
.directive('navbar', function () {
return {
templateUrl: '../../views/navbar.html',
replace: 'true',
restrict: 'E',
scope: {
email: '='
},
link: function (scope, elem, attrs) {
scope.$on('userLoggedIn', function (event, args) {
scope.email = args.email;
});
scope.$on('userLoggedOut', function (event) {
scope.email = false;
console.log(newValue);
});
}
}
});
and emitting your events in the controller like this:
$rootScope.$broadcast('userLoggedIn', user);
This feels like such a hack I hope the angular gurus can see this post and provide a better answer, but as it is the accepted answer does not even work and just gives the error $digest already in progress
Using $apply() like the accepted answer can cause all sorts of bugs and potential performance hits as well. Settings up broadcasts and whatnot is a lot of work for this. I found the simple workaround just to use the standard timeout to trigger the event in the next cycle (which will be immediately because of the timeout). Surround the parentUpdate() call like so:
$timeout(function() {
$scope.parentUpdate();
});
Works perfectly for me. (note: 0ms is the default timeout time when not specified)
One thing most people forget is that you can't just declare an isolated scope with the object notation and expect parent scope properties to be bound. These bindings only work if attributes have been declared through which the binding 'magic' works. See for more information:
https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/
Instead of using $scope.$apply(), try using $scope.$applyAsync();

how to set an interpolated value in angular directive?

How do I set the interpolated value in a directive? I can read the correct value from the following code, but I have not been able to set it.
js:
app.directive('ngMyDirective', function () {
return function(scope, element, attrs) {
console.log(scope.$eval(attrs.ngMyDirective));
//set the interpolated attrs.ngMyDirective value somehow!!!
}
});
html:
<div ng-my-directive="myscopevalue"></div>
where myscopevalue is a value on my controller's scope.
Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to change that property's value, I suggest using $parse. (I think the syntax is nicer than $eval's.)
app.directive('ngMyDirective', function ($parse) {
return function(scope, element, attrs) {
var model = $parse(attrs.ngMyDirective);
console.log(model(scope));
model.assign(scope,'Anton');
console.log(model(scope));
}
});
fiddle
$parse works whether or not the attribute contains a dot.
If you want to set a value on the scope but don't know the name of the property (ahead of time), you can use object[property] syntax:
scope[attrs.myNgDirective] = 'newValue';
If the string in the attribute contains a dot (e.g. myObject.myProperty), this won't work; you can use $eval to do an assignment:
// like calling "myscopevalue = 'newValue'"
scope.$eval(attrs.myNgDirective + " = 'newValue'");
[Update: You should really use $parse instead of $eval. See Mark's answer.]
If you're using an isolate scope, you can use the = annotation:
app.directive('ngMyDirective', function () {
return {
scope: {
theValue: '=ngMyDirective'
},
link: function(scope, element, attrs) {
// will automatically change parent scope value
// associated by the variable name given to `attrs.ngMyDirective`
scope.theValue = 'newValue';
}
}
});
You can see an example of this in this Angular/jQuery color picker JSFiddle example, where assigning to scope.color inside the directive automatically updates the variable passed into the directive on the controller's scope.

Resources