Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了AngularJS – 从子目录访问父指令属性大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这不应该是太难的事情,但我不知道如何最好地做到这一点.

我有一个父指令,就像这样:

directive('editableFieldset',function () {
  return {
    reStrict: 'E',scope: {
      model: '='
    },replace: true,transclude: true,template: '
      <div class="editable-fieldset" ng-click="edit()">
        <div ng-transclude></div>

        ...

      </div>',controller: ['$scope',function ($scope) {
      $scope.edit = ->
        $scope.ediTing = true

       // ...
    ]
  };
});

一个孩子指令:

.directive('editableString',template: function (element,attrs) {
      '<div>
        <label>' + attrs.label + '</label>
        <p>{{ model.' + attrs.field + ' }}</p>

        ...
      </div>'
    },require: '^editableFieldset'
  };
});

如何从子指令中轻松访问模型并编辑父指令的属性?在我的链接函数中,我可以访问父范围 – 应该使用$watch来监视这些属性吗?

放在一起,我想要的是:

<editable-fieldset model="mymodel">
  <editable-String label="Some Property" field="property"></editable-String>
  <editable-String label="Some Property" field="property"></editable-String>
</editable-fieldset>

这个想法是显示一组字段.如果点击,它们就成为输入,可以编辑.

this SO post开始,我有一个工作解决方here in this plunker.

我不得不改变一点点.我选择在editableString上有一个孤立的范围,因为它更容易绑定到模板的正确的值.否则,您将不得不使用编译或其他方法(如$transclude服务).

结果如下:

JS:

var myApp = angular.module('myApp',[]);

myApp.controller('Ctrl',function($scopE) {

  $scope.mymodel = { property1: 'Hello1',property2: 'Hello2' }

});


myApp.directive('editableFieldset',template: '<div class="editable-fieldset" ng-click="edit()"><div ng-transclude></div></div>',link: function(scope,element) {
      scope.edit = function() {

        scope.ediTing = true;
      }
    },function($scopE) {

      this.getModel = function() {
        return $scope.model;
      }

    }]
  };
});

myApp.directive('editableString',scope: {
      label: '@',field: '@'
    },template: '<div><label>{{ label }}</label><p>{{ model[field] }}</p></div>',require: '^editableFieldset',element,attrs,ctrl) {

      scope.model = ctrl.getModel();
    }
  };
});

HTML:

<body ng-controller="Ctrl">
    <h1>Hello Plunker!</h1>
    <editable-fieldset model="mymodel">
      <editable-String label="Some Property1:" field="property1"></editable-String>
      <editable-String label="Some Property2:" field="property2"></editable-String>
    </editable-fieldset>
  </body>

大佬总结

以上是大佬教程为你收集整理的AngularJS – 从子目录访问父指令属性全部内容,希望文章能够帮你解决AngularJS – 从子目录访问父指令属性所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。