AngularJS在自定义指令中传递Model

本文是对AngularJS权威指南8.2节的理解,书中的解释比较混乱,花了一些时间才理解作者表达的意思。

假如我们创建了一个指令,用于生成一个包含input和a标签。如果我们想input标签的内容通过ng-model的方式传递出去(例如传递到指令外的另一个input),我们可能会这么写:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="angular.js"></script>
</head>
<body>
<input type="text" ng-model="myUrl"/>
<div my-directive
     some-attr="{{myUrl}}"
     my-link-text="Click me to go to Google"></div>
<script>
    angular.module('myApp', [])
            .directive('myDirective', function() {
                return {
                    restrict: 'A',
                    replace: true,
                    scope: {
                        myUrl: '@someAttr',
                        myLinkText: '@'
                    },
                    template: '
          <div>
            <input type="text" ng-model="myUrl" />
            <a href="{{myUrl}}">{{myLinkText}}</a>
          </div>
        '
                }
            })
</script>
</body>
</html>

生成的HTML如下图所示:

这里写图片描述

但是这不能达到我们的预期:数据只能从第一个input传递到第二个input,而不能从第二个input传递到第一个input。

原因是指令内部有独立的作用域,指令内的{{myUrl}}不能直接被外部共享。

将代码做如下修改,可以实现被外部共享,注意修改的部分有注释:

<!doctype html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8"/>
    <script src="angular.js"></script>
</head>
<body>
<input type="text" ng-model="myUrl"/>
<!--*****************************************-->
<!--{{myUrl}}改为了myUrl-->
<div my-directive
     some-attr="myUrl"
     my-link-text="Click me to go to Google"></div>
<!--*****************************************-->
<script>
    angular.module('myApp', [])
            .directive('myDirective', function() {
                return {
                    restrict: 'A',
                    replace: true,
                    scope: {
                        //*****************************************
                        myUrl: '=someAttr',//@修改为了=
                        //*****************************************
                        myLinkText: '@'
                    },
                    template: '
          <div>
            <input type="text" ng-model="myUrl" />
            <a href="{{myUrl}}">{{myLinkText}}</a>
          </div>
        '
                }
            })
</script>
</body>
</html>

总结

指令内部model共享到外部,只需要将”@”改为”=”,并且将对应的指令的{{}}删掉即可。

原文地址:https://www.cnblogs.com/qs20199/p/4452266.html