After doing some research, I have not been able to find a solution that addresses my particular issue.
Here is what I know:
ng-if
andng-repeat
create isolated scopes.- Avoid using
$parent.someProperty
. - Using
$parent.$parent.someProperty
is strongly discouraged.
Given the template markup provided, how can I correctly bind the controller so that the controller property updates as desired?
Markup:
(Take note of the nested ng-if
and ng-repeat
, resulting in a pseudo $parent.$parent
scenario)
<div ng-app="MyApp" ng-controller="MyCtrl">
<div ng-if="showOnCondition">
<label ng-repeat="item in repeatingItems">
{{item}}
<setting item="item" />
</label>
</div>
{{checkSetting()}}
</div>
JavaScript
var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.settings = {
someProperty: '',
anotherProperty: 'Hello'
}
$scope.repeatingItems = [
'One',
'Two',
'Three'
];
$scope.showOnCondition = true;
$scope.checkSetting = function() {
// The goal is to access the value of someProperty here when calling checkSettings()
return $scope.settings;
}
});
myApp.directive('setting', function() {
return {
restrict: 'E',
require: '^myCtrl',
// How can this be properly resolved?
// Avoid using $parent.$parent
template: '<input type="radio" ng-model="$parent.$parent.settings.someProperty" name="mySetting" value="{{item}}" />',
scope: {
settings: '=',
item: '='
}
};
});
In the example above, how do I construct the directive or modify the markup to have access to settings.someProperty
within the controller? Or is there potentially a different approach that should be followed?
Clarification
To clarify, the someProperty
is accessible within the directive - this part works fine. My intention is to set values for the controller's someProperty
from within the directive (using ng-model).
Update
I have revised the code snippet with known functioning code and included a link to a working jsFiddle.
While this solution does work, it relies on using $parent.$parent
in the template. Finding an alternative to this is the challenge at hand.