问题
After reviewing AngularJS (and related) documentation and other stackoverflow questions regarding isolated scopes within directives, I'm still a little confused. Why can't I do a bi-directional binding between the parent scope and directive isolated scope, where the parent scope property is an object and not an attribute? Should I just use the desired property off scope.$parent
? That seems wrong. Thanks in advance for your help.
The related fiddle is here.
HTML:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div my-directive>{{test.name}}</div>
</div>
</div>
JavaScript:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function ($scope) {
$scope.test = {name:"name", value:"value"};
});
myApp.directive("myDirective", function () {
return {
replace: true,
restrict: 'A',
scope: {test: '='},
template: '<div class="parent"><div>This is the parent Div.</div><div>Value={{test}}</div></div>',
link: function (scope, element, attrs) {
console.log("scope.test=["+scope.test +"]");
console.log("scope.$parent.test=["+scope.$parent.test.name+"]");
}
};
});
回答1:
For directives using an isolate scope, attributes are used to specify which parent scope properties the directive isolate child scope will need access to. '=' provides two-way binding. '@' provides "one-way strings". '&' provides one-way expressions.
To give your directive (two-way binding) access to parent scope object property test
, use this HTML:
<div my-directive test="test"></div>
It might be more instructive to use different names:
<div my-directive some-obj-prop="test"></div>
Then in your directive:
scope: { localDirProp: '=someObjProp'},
template: '<div ...>Value={{localDirProp}}...',
Isolate scopes do not prototypically inherit from the parent scope, so it does not have access to any of the parent scope's properties (unless '@' or '=' or '&' are used). Using $parent
is a way to still access the parent scope, but not via prototypical inheritance. Angular creates this special $parent
property on scopes. Normally (i.e. best practice), it should not be used.
来源:https://stackoverflow.com/questions/15536435/how-can-i-inherit-complex-properties-from-the-parent-scope-into-my-directives-i