指令中的Ng-repeat丢失范围

时间:2015-07-03 05:51:54

标签: javascript angularjs

我遇到了指令

范围内的问题

尝试以下链接(尝试第二个和第三个输入框,他们应该共享相同的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>

2 个答案:

答案 0 :(得分:1)

根据Angular文档,ng-repeat创建一个新范围。

您可以在此处详细了解:https://docs.angularjs.org/api/ng/directive/ngRepeat

答案 1 :(得分:1)

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

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 : '='
        }
    };
});