angularjs - 如何在 AngularJS 中通过属性将对象传递给指令?

标签 angularjs angularjs-directive

我想通过 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/

相关文章:

javascript - 有人在 AngularJS 中使用 vis.js 吗?

javascript - ng-show 不在表中工作,而相同的语句在 div 主体中工作

javascript - 无法以 Angular 访问 Controller 内部的变量

javascript - AngularJS - 计时器指令。与模态视图共享间隔

html - 无法在 bootstrap 模式中将输入集中在 qtip 中

javascript - 2 路数据绑定(bind)指令 Angular

javascript - 如何将绑定(bind)表达式作为文本传递到指令隔离范围?

angularjs - 测试 modalInstance.result.then

angularjs - 具有多个角色的 Angular SPA

angularjs - jhipster 应用程序中的 has-any-authorithy 指令