2015-07-03 107 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