2015-10-06 100 views
1

我是角度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

+0

好事,第一解决方案,但主要和第二个问题的结合并没有奏效http://jsfiddle.net/VJ94U/1366/ – codeofnode

回答

1

您可以实现您的自定义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", 
     } 
    } 
    }); 
+0

不错,但我的指令也有其他各种属性,我不想一次又一次地放入模板中。 – codeofnode

+0

在 – ZenDD

+0

上面添加了一些编辑我找不到在ng-bind绑定中的2路绑定..请参阅setTimeout here http://jsfiddle.net/VJ94U/1367/ – codeofnode