zl程序教程

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

当前栏目

[Angular]Isolate scope "=", two ways bindings

Angular quot two Scope Ways
2023-09-14 09:00:56 时间
<!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 ng-controller="AppCtrl">
                Ctrl
              <input type="text" ng-model="ctrlFlavor">
              Dir
              <div drink flavor="ctrlFlavor"></div>
            </div>
          </div>
    </body>
</html>
var app = angular.module("drinkApp", []);

app.controller("AppCtrl", function($scope) {
    $scope.ctrlFlavor = "blackberry"
})

/**
    scope: {flavor: "="}, "=", two ways binding, accept an object,
    different with @ which accpes a string,
    so in html, you don't use: {{}}, it expects a string
     <div drink flavor="{{ctrlFlavor}}"></div>
    you should do:
     <div drink flavor="ctrlFlavor"></div>
     
    So whenever the value changed in template, it will send to ctrlFlavor
    thought flavor
*/
app.directive("drink", function() {
    return {
        scope: {flavor: "="},
        template: '<input type="text" ng-model="flavor">'
    }
})

所谓的two ways binding,就是指,directive 中的scope的flavor去绑定controller中的scope的attr.

So, one changed, the other also changed!