2015-07-03 67 views
1

我遇到了一个问题,范围指令中伍重复失去范围

试试下面的链接(尝试他们应该共享相同的NG-模型的第二和第三个输入框)

https://output.jsbin.com/rudimihuha

基本上我有一个指令和一个ng-rpeat,在某种程度上,范围在ng-repeat内丢失了,为什么它会这样做呢?

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script> 
    <meta charset="utf-8"> 
<!-- 
Created using JS Bin 
http://jsbin.com 

Copyright (c) 2015 by anonymous (http://jsbin.com/rudimihuha/1/edit) 

Released under the MIT license: http://jsbin.mit-license.org 
--> 
<meta name="robots" content="noindex"> 
    <title>JS Bin</title> 
</head> 
<body ng-app="MyApp"> 
<test></test> 
<script> 
var myApp = angular.module('MyApp', []); 
console.log('hit'); 

myApp.directive('test', function() { 
    return { 
     restrict: 'E', 
     template: "<div>inertanl - {{formResult}} <input type=\"text\" ng-model=\"formResult\"> <div> <div ng-repeat=\"(key, value) in ['test', 'test2']\"> <input type=\"text\" ng-model=\"formResult\"> </div></div>", 
     replace: true, 
     scope: { 
      ngModel : '=' 
     } 
    }; 
}); 
</script> 
<script src="https://static.jsbin.com/js/render/edit.js?3.30.3"></script> 
<script>jsbinShowEdit && jsbinShowEdit({"static":"https://static.jsbin.com","root":"https://jsbin.com"});</script> 
<script src="https://static.jsbin.com/js/vendor/eventsource.js?3.30.3"></script> 
<script src="https://static.jsbin.com/js/spike.js?3.30.3"></script> 
<script> 
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 
})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 
ga('create', 'UA-1656750-34', 'jsbin.com'); 
ga('require', 'linkid', 'linkid.js'); 
ga('require', 'displayfeatures'); 
ga('send', 'pageview'); 

</script> 

</body> 
</html> 

回答

1

约翰尼说的范围是不一样的。如果你想从你的孩子可以做$父访问父范围(下面的代码将保持同步,所有的输入)

var myApp = angular.module('MyApp', []); 
console.log('hit'); 

myApp.directive('test', function() { 
    return { 
     restrict: 'E', 
     template: "<div>inertanl - {{formResult}} <input type=\"text\" ng-model=\"formResult\"> <div> <div ng-repeat=\"(key, value) in ['test', 'test2']\"> <input type=\"text\" ng-model=\"$parent.formResult\"> </div></div>", 
     replace: true, 
     scope: { 
      ngModel : '=' 
     } 
    }; 
}); 
+0

有什么比$父更好的办法?只是好奇的伴侣 – Bruce

+0

是的,你应该使用'$ parent',也就是'data-ng-init' – Vineet

+0

@Vineet请给出一个示例队友,我正在寻找更好的解决方案。 – Bruce