zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular] Isolate Scope "@"

Angular quot Scope
2023-09-14 08:59:21 时间
var app = angular.module("drinkApp", []);

/**
    scope:{flavor: "@"} has the same affect as
    link: function(scope, element, attrs){
        scope.flavor = attrs.flavor;
    }
    Because attrs.flavor is a string,
    @ : take affect like attrs
*/
app.directive("drink", function() {
  return {
    scope:{flavor: "@"},
    template: '<div>{{flavor}}</div>'//,
    /*link: function(scope, element, attrs){
        scope.flavor = attrs.flavor; //attrs.flavor="strawberrey"
    }*/
  }
});

/*
    <div ng-controller="AppCtrl" drink flavor="{{ctrlFlavor}}"></div>
    If controller wants to talk with directive, drink attribute should be added
    into the code, otherwise wont work;
    
    since @ works as attrs, will get attrs.flavor = {{ctrlFlavor}},
    attrs.flavor = "Blackberry"
*/
app.controller("AppCtrl", function($scope){
    $scope.ctrlFlavor = "Blackberry"
});

 

<!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="drinkApp">
            <div drink flavor="strawberrey"></div>
            <hr/>
            <div ng-controller="AppCtrl" drink flavor={{ctrlFlavor}}></div>
        </div>
        </div>
    </body>
</html>