美文网首页
AngularJS自定义指令隔离作用域

AngularJS自定义指令隔离作用域

作者: JasonQiao | 来源:发表于2016-02-04 11:51 被阅读556次

看ng book1里面第十章的隔离作用域,我对里面的例子稍加修改以证明隔离作用域和外部作用域是不能互相访问的。代码如下

<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js">
</head>
<body ng-init="outerProperty = 'wow, this is hot'">

  Outside myDirective: {{ myProperty }}
  Outside Property: {{ outerProperty }}

  <div my-directive ng-init="myProperty = 'wow, this is cool'">
    Inside myDirective: {{ myProperty }}
    Outside Property: {{ outerProperty }}
  <div>

  <script>
    angular.module('myApp', [])
    .directive('myDirective', function() {
      return {
        restrict: 'A',
        scope: {}
      };
    })
  </script>

</body>
</html>

运行结果是

Outside myDirective:
Outside Property: wow, this is hot
Inside myDirective: wow, this is cool
Outside Property: 

但是当我把angularJS换成高版本的。例如1.2.13,1.5.0却发现这个结果不一样了。

Outside myDirective: wow, this is cool 
Outside Property: wow, this is hot
Inside myDirective: wow, this is cool 
Outside Property: wow, this is hot

难道新版AngularJS不支持隔离作用域了?于是在AngularJS官网上找隔离作用域,看到新版隔离作用域的用法。
隔离作用域主要是创建可复用组件,同时我们还希望外部作用域可以把部分值传递给隔离作用域使用。scope配置项是一个包含绑定作用域属性的对象。例如scope: { customerInfo: '=info'}将customerInfo同外部属性info的值进行绑定。这样才能在隔离作用域使用info值指定的属性值。其他外部的值不能再隔离作用域使用。
例子经过修改,如下

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example18-production</title>
  
  <script src="../angular/1.2.13/angular.js"></script>
  <script>
  (function(angular) {
    'use strict';
  angular.module('docsIsolationExample', [])
    .controller('Controller', ['$scope', function($scope) {
      $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
      $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
    }])
    .controller('anotherController', ['$scope', function($scope) {
      $scope.jason = { name: 'Yanfei Qiao', address: 'No. 518 Xinzhuan Rd.' };
    }])
    .directive('myCustomer', function() {
      return {
        restrict: 'E',
        scope: {
          customerInfo: '=info'
        },
        template: 'Name: {{customerInfo.name}} Address: {{customerInfo.address}} \
                  <hr> \
                  Name: {{vojta.name}} Address: {{vojta.address}}'
      };
    });
  })(window.angular);
  </script>
  
</head>
<body ng-app="docsIsolationExample">
  <div ng-controller="Controller">
    <my-customer info="naomi"></my-customer>
  </div>
  <div ng-controller="anotherController">
    <my-customer info="jason"></my-customer>
  </div>
</body>
</html>

输出结果如下

Name: Naomi Address: 1600 Amphitheatre
Name: Address:
Name: Yanfei Qiao Address: No. 518 Xinzhuan Rd.
Name: Address:

相关文章

网友评论

      本文标题:AngularJS自定义指令隔离作用域

      本文链接:https://www.haomeiwen.com/subject/bvpekttx.html