如何$scope.attributes
在html中显示数组?
例如多次按下按钮后如何显示JSON集合
[{'row'},{'tout'},{'row'}]
..等等
有没有更好的方法来执行此操作,例如将指令对象返回给父控制器?即使这不是正确的方法,您也会怎么做..大声笑?
html
<div ng-app="docsSimpleDirective">
<div ng-controller="Ctrl">
<h4>directive to directive communication</h4>
<btn row></btn>
<btn tout></btn>
{{btn.attributes | json}}
</div>
</div>
JS
angular.module('docsSimpleDirective', [])
.controller('Ctrl', function($scope) {
$scope.attributes = [];
$scope.alertMessage = function(message) {
alert(message);
}
$scope.applyAlert = function() {
alert('asdlfkjsadlfkj');
}
})
.directive('btn', function() {
return {
restrict: 'E',
scope: {},
controller: function ($scope) {
$scope.attributes = []
this.addRow = function() {
$scope.attributes.push('row')
}
this.addTout = function() {
$scope.attributes.push('tout')
}
},
link: function(scope, element) {
element.bind('click', function(){
console.log(scope.attributes);
})
}
};
})
.directive('row', function() {
return{
restrict: 'A',
require: 'btn',
template: '<button>add Row</button>',
link: function(scope, element, attrs, btnCtrl) {
btnCtrl.addRow();
}
};
})
.directive('tout', function() {
return{
restrict: 'A',
require: 'btn',
template: '<button>add tout</button>',
link: function(scope, element, attrs, btnCtrl) {
btnCtrl.addTout();
}
};
})
这是更新的小提琴。
由于您声明btn
为隔离范围(scope: {}
),因此您无法影响控制器的范围(不需要它)。
在此HTML中:
<div ng-app="docsSimpleDirective">
<div ng-controller="Ctrl">
<h4>directive to directive communication</h4>
<btn row></btn>
<btn tout></btn>
{{btn.attributes | json}}
</div>
</div>
btn.attributes
在控制器的范围内。它不在的范围内btn
。作用域的角度总是挂在其上需要它们的DOM元素的关。
同样,该btn
属性或控制器都未声明名为的作用域属性btn.attributes
。他们俩都宣布正义attributes
。
因此,如果我们使用以下HTML:
<div ng-app="docsSimpleDirective">
<div ng-controller="Ctrl">
<hr /> <hr /> <hr />
<h4>directive to directive communication</h4>
<btn row></btn>
<btn tout></btn>
{{attributes}}
</div>
</div>
脱开孤立的示波器,您将开始获得想要的结果。因此,一种实现此目的的方法是不使btn
隔离范围:
.directive('btn', function() {
return {
restrict: 'E',
controller: function ($scope) {
this.addRow = function() {
$scope.attributes.push('row')
}
this.addTout = function() {
$scope.attributes.push('tout')
}
},
link: function(scope, element) {
element.bind('click', function(){
console.log(scope.attributes);
})
}
};
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句