[Angular] Isolate Scope. 1

This demo shows that three directive 'require' from another directive.

<!DOCTYPE html>
<html>
    <head>
        <title>Angular Directive</title>
        <link rel="stylesheet" href="foundation.min.css" />
        <script src="angular.min.js"></script>
        <script src="main.js"></script>
    </head>
    <body >
     <div ng-app="superApp">
        <superhero flight speed strength>Superman</superhero>
        <superhero speed>The Flash</superhero>
        <superhero strength>The Hulk</superhero>
      </div>
    </body>
</html>

 

var app = angular.module("superApp", []);

app.directive("superhero", function() {
    return {
        restrict: "E",
        scope: {},

        controller: function($scope) {
            $scope.abilities = []

            this.addStrength = function() {
                $scope.abilities.push("strength")
            }

            this.addSpeed = function() {
                $scope.abilities.push("speed")
            }

            this.addFlight = function() {
                $scope.abilities.push("flight")
            }
        },

    link: function(scope, element) {
        element.addClass("button");
        element.bind("mouseenter", function() {
            console.log(scope.abilities);
        })
    }
  }
});

//depend on superhero directive
app.directive("strength", function() {
    return {
        require: "superhero",
        link: function(scope, element, attrs, superheroCtrl) {
            superheroCtrl.addStrength();
        }
    }
})

//depend on superhero directive
app.directive("speed", function() {
    return {
        require: "superhero",
        link: function(scope, element, attrs, superheroCtrl) {
            superheroCtrl.addSpeed();
        }
    }
})

//depend on superhero directive
app.directive("flight", function() {
    return {
        require: "superhero",
        link: function(scope, element, attrs, superheroCtrl) {
            superheroCtrl.addFlight();
        }
    }
})

In superhero directive, we also have controller, which provides API for other directives. 

The most important things is:

scope: {},

This is called isolate scope, If you don't have this, three directive will affect on the same scope, so it will override each other, therefor you need to add this line code in your directive. To avoid scope been overrided.

posted @ 2014-08-14 03:24  Zhentiw  阅读(227)  评论(0)    收藏  举报