Tuesday 17 October 2017

javascript - Angularjs Directive with Isolated Scope doesn't trigger DOM change outside of directive

itemprop="text">


I'm playing around angular
directives with isolated scopes.
I've just faced an interesting situation.
When I call a function from the local scope, which changes a $scope variable content,
this is not affecting the DOM. In my example, I add a new element to the
$scope.customers list, and this is not triggering the ngRepeat, so this part of the DOM
is not affected where the ngRepeat items should be
rendered.



Directive
code:



function addItem()
{
scope.add();
items.push({
name: 'New Directive
Customer'

});
scope.$broadcast("refresh");

render();
}
...
return {
restrict:
'EA',
scope: {
datasource: '=',
add:
'&',

},
link:
link
};


Local
function code:



$scope.addCustomer
= function() {
counter++;

$scope.customers.push({

name: 'New Customer' + counter,

street: counter + ' Cedar Point St.'
});


alert($scope.customers.length);
};


DOM
ngRepeat
part:




            datasource="customers"
add="addCustomer()">
/>


  • {{customer.name}}






The
alert() will show that the
$scope.customers is bigger after every button click, but the
ngRepeat won't work on the DOM.




The
full code:
rel="nofollow">http://plnkr.co/edit/8tUzKbKxK0twJsB6i104



My
question is that, is this possible to trigger the DOM changes from this kind of
directives somehow?



Thanks in
advance



Answer




Your plunkr only worked for me after removing
the check for event.srcElement.id in the directive's
click-callback.





function addItem() {
//Call external function passed in with &

scope.add();

//Add new customer to the local collection

items.push({
name: 'New Directive Customer'

});



scope.$broadcast("refresh");

render();

}


In the controller
you have to use $scope.$apply to make the changes appear in the
template:



 $scope.addCustomer =
function() {
$scope.$apply(function(){

counter++;

$scope.customers.push({
name: 'New Customer'
+ counter,
street: counter + ' Cedar Point St.'

});


});


href="http://plnkr.co/edit/lGmGiPIqEm2AA8cngkHz?p=preview"
rel="nofollow">http://plnkr.co/edit/lGmGiPIqEm2AA8cngkHz?p=preview



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...