我是 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/