繁体   English   中英

如何在自定义属性指令中访问父范围

[英]How to access parent scope in custom attribute directive

我是angular js的入门者。

我遇到了类似的问题, 如何在AngularJS中通过具有自己作用域*的自定义指令访问父作用域?

但是答案对我的简单实验没有用。

这是沙盒。 http://jsfiddle.net/VJ94U/1364/

angular.module('mod', []).
directive('myBind', function() {
  return {
    restrict : 'A',
    scope : {
      scopeVar : '@'
    },
    link : function(scope,element,attr){
      element.attr('ng-bind', scope.scopeVar);
      element.text(scope.scopeVar);
    }
  };
});


var app = angular.module('app', [ 'mod' ]);
angular.element(document).ready(function() {
  angular.module('app').run(function($rootScope){
    $rootScope.scopeVar = 'This is scope variable.';
  });
  angular.bootstrap(document, ['app']);
});

我只是想要我自己的my-bind (作为ng-bind副本)

因此,属性my-bind值是一些scopeVariable的名称,并且每当该范围变量值更改时,div的内容都应使用该更新后的值进行更新。

我既没有获得父范围变量值,也没有得到相应的文本。

PS:我知道我应该使用=但我至少从@开头检查以查找范围变量并使用它的值。 PS:我也想避免使用$parent

您可以将自定义ng-bind为一个简单的指令,如下所示:

<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="scopeVar"><br>
  <div my-bind data="scopeVar"></div>
</div>

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.scopeVar = "Bind me";
  }])
  .directive("myBind", function(){
    return {
      template: "<p ng-bind='myVar'></p>",
      scope: {
        myVar: "=data",
      }
    }
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM