Angularjs 嵌套指令与原型继承
通常在使用隔离作用域时,我使用中间vm对象传递模型对象,以避免原型继承问题 喂,我有一个指令Angularjs 嵌套指令与原型继承,angularjs,Angularjs,通常在使用隔离作用域时,我使用中间vm对象传递模型对象,以避免原型继承问题 喂,我有一个指令 function directiveA() { return { restrict: 'E', scope: { myParam: '=' }, ... } } 我想在html中这样称呼它: <directive-a my-param="vm.someProperty"></directiv
function directiveA() {
return {
restrict: 'E',
scope: {
myParam: '='
},
...
}
}
我想在html中这样称呼它:
<directive-a my-param="vm.someProperty"></directive-a>
因此,如果在directiveB中我为scope.myParam分配了一个新值,它将在directiveB的作用域上创建一个新对象,而不是修改directiveA作用域上的myParam属性
我怎样才能避免这个问题 简短回答 为了避免这个问题,将vm的整个对象传递给scope指令
<directive-a my-param="vm"></directive-a>
返回原始问题 正如在简短回答中所说的,将隔离范围设置为通过引用传递不会创建新范围,任何更改都会修改其父范围 这是问题的解决方案 HTML
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>AngularJS: Nested Directives Accessing Scope Directives</title>
</head>
<body>
<div class="main" ng-controller="appController">
<directive-a my-param="vm">
<directive-b my-param="vm"></directive-b>
</directive-a>
</div>
</body>
</html>
希望这能帮到你。干杯你如何使用
指令b
?根据这一点,它甚至可能无法访问目录a的范围。
<directive-b my-param="vm"></directive-b>
// Pass By Value
var a = "helloProperty";
var b = a;
b = "modifiedProperty";
console.log(a); // prints helloProperty
// Pass By Value
var c = {};
c.someProperty = "helloProperty2";
var d = c.someProperty;
d = "modifiedProperty2";
console.log(c); // prints helloProperty2
// Pass By Reference
var e = {};
e.someProperty = "helloProperty3";
var f = {};
f = e;
f.someProperty = "modifiedProperty3";
console.log(e); // prints modifiedProperty3
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>AngularJS: Nested Directives Accessing Scope Directives</title>
</head>
<body>
<div class="main" ng-controller="appController">
<directive-a my-param="vm">
<directive-b my-param="vm"></directive-b>
</directive-a>
</div>
</body>
</html>
var app = angular.module('myApp',['myApp.controller', 'myApp.directive']);
angular.module('myApp.controller', []).controller('appController', ['$scope', function($scope){
$scope.vm = {
someProperty: ''
};
$scope.vm.someProperty = 'someVmProperty';
}]);
angular.module('myApp.directive', [])
.directive('directiveA', function(){
return {
restrict: 'E',
scope: {
myParam: '='
},
controller: ['$scope', function($scope){
}],
link: function(scope, element, attrs){
console.log(scope.myParam); // prints Object {someProperty: "modifiedProperty"}
}
}
}).
directive('directiveB', function(){
return {
restrict: 'E',
require: '^directiveA',
scope: {
myParam: '='
},
controller: ['$scope',function($scope){
}],
link: function(scope, element, attrs){
scope.myParam.someProperty = 'modifiedProperty';
}
}
});