I've been experimenting with bound variables inside directives, but I'm facing an issue where the view doesn't seem to refresh. Despite the model updating correctly (as seen in the console log) and calling $apply(), the view remains unchanged. Check out the example on jsfiddle!
Here's the HTML snippet:
<div ng-app="foo">
<div ng-controller="MyCtrl">
<div my-directive val="val" checked="checked" refresh="refresh"></div>
<p>val (outside directive): {{val}}<p/>
<p>checked (outside directive): {{checked}}<p/>
</div>
</div>
And here's the corresponding JavaScript code:
angular.module('foo', []).directive('myDirective', function() {
return {
restrict: 'A',
scope: {
val: "=",
checked: "=",
refresh: "="
},
template: '<p>val (inside directive): {{val}}</p>' +
'<p>checked (inside directive): {{checked}}</p>' +
'<input type="checkbox" ng-model="checked">checked',
link: function(scope, element, attrs) {
var count = 0;
//scope.val = "initialized";
scope.$watch('checked', function() {
scope.val = "new value" + count;
count += 1;
console.log("updated val is: " + scope.val);
scope.refresh();
});
} // link
}; // return
}); // angular.module
function MyCtrl($scope) {
$scope.val = "initial value";
$scope.checked = false;
$scope.$watch('val', function(newVal) {
console.log("newVal is: " + newVal);
});
$scope.refresh = function() {
// none of the following lines make a difference
if(!$scope.$$phase) $scope.$apply();
// $scope.$apply();
// if(!$scope.$$phase) $scope.$digest();
// $scope.$digest();
console.log("val is: " + $scope.val);
console.log("checked is: " + $scope.checked);
}; // refresh
} // MyCtrl