AngularJS之scope独立作用域

半兽人 发表于: 2018-10-02   最后更新时间: 2022-09-20 16:24:53  
{{totalSubscript}} 订阅, 3,144 游览

本节介绍AngularJS的独立作用域scope,我们先看段代码:

<!doctype html>
<html ng-app="MyModule">
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
    </head>
    <body>
        <hello></hello>
        <hello></hello>
        <hello></hello>
        <hello></hello>
    </body>
    <script src="framework/angular-1.3.0.14/angular.js"><//script>
    <script src="IsolateScope.js"><//script>
</html>

js:

var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
    return {
        restrict: 'AE',
        template: '<div><input type="text" ng-model="userName"/>{{userName}}</div>',
        replace: true
    }
});

我们先定义一个hello的指令,我们在template模板上,增加了一个用户输入<input type="text" ng-model="userName"/>{{userName}}</div>,也会增加了一个双向数据绑定{{userName}}

运行结果:

我就不截图了,4个input标签,你输入的内容会同时发送变化,是共享的。

任意一个指令发送变化的时候,会影响到其他3个指令的值。

这样就导致你没办法复用指令了,解决的方法很简单,你只需要增加一个scope:{},就可以了,完整js代码:

var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
    return {
        restrict: 'AE',
        scope:{},
        template: '<div><input type="text" ng-model="userName"/>{{userName}}</div>',
        replace: true
    }
});

现在,指令之间就不会互相影响了。

更新于 2022-09-20

查看AngularJS更多相关的文章或提一个关于AngularJS的问题,也可以与我们一起分享文章