javascript - 如何访问自定义属性指令中的父范围

标签 javascript angularjs

我是 Angular JS 的初学者。

我遇到了类似的问题How to access parent scope from within a custom directive *with own scope* in 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",
      }
    }
  });

关于javascript - 如何访问自定义属性指令中的父范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32973644/

相关文章:

c# - 如何在服务器 ASP.NET 上请求客户端 cookie

javascript - Rails 4 - JavaScript 停止工作,获取 : undefined is not a function

javascript - Angular UI 路由器 : Different states with same URL?

javascript - AngularJS:类型错误:无法设置未定义的属性

javascript - Angular JS : How can i fire ng-blur on input field as soon as is displayed?

javascript - 已解决 : how can i break a for loop based on a response from promise?

JavaScript 将许多函数括起来

javascript - 在 JS/JQuery 中,我可以从多维数组中提取单个元素并将其存储在另一个数组中吗?

javascript - 在 Angular 中切换一个 div

javascript - AngularJS 使用 ng-repeat 重绘 div 列表