我想通过 ATTRIBUTE 而不是通过隔离范围传递对象(引用 - 双向绑定(bind))。我怎样才能做到这一点?因为下面的代码传递字符串而不是对象:
HTML
<tr ng-form="rowForm" myDirective="{{row.data}}">
指令
angular.module("app").directive("myDirective", function () {
return {
require: ["^form"],
restrict: "A",
link: function (scope, element, attrs, ctrls) {
scope.$watch(function () {
return attrs.myDirective;
}, function (newValue, oldValue) {
// .....
最佳答案
指令可以进行双向数据绑定(bind),无需手动解析或编译任何内容,很抱歉没有提供 plunker,但它是叛逆的,不会为我节省
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.myObj = {name: 'Tibro', age: 255}
})
.directive('myDirective', function(){
return {
scope: {
'myAttribute': '='
},
template: '{{myAttribute}}',
link: function(scope){
scope.myAttribute.age= 31
}
}
})
HTML
<body ng-controller="MainCtrl">
controller: {{myObj}} <br/>
directive: <my-directive my-attribute="myObj"></my-directive>
</body>
<小时/>
输出
controller: {"name":"Tibro","age":31}
directive: {"name":"Tibro","age":31}
您可以从输出中看到传递的对象已被双向绑定(bind),并且指令中所做的更改反射(reflect)在 Controller 级别
关于angularjs - 如何在 AngularJS 中通过属性将对象传递给指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40828050/