【问题标题】:why is $watch value parameter sometimes a string value and sometimes a function?为什么 $watch value 参数有时是字符串值,有时是函数?
【发布时间】:2015-12-21 14:15:45
【问题描述】:

我见过 $watch 的第一个参数只是一个字符串而不是函数的情况。什么时候用函数,什么时候用字符串?

在这个 plunker 中,我以两种方式都这样做了。控制器中的 $watch 使用函数,而指令中的 $watch 使用字符串。它们都有效,但我只是不明白为什么它在一种情况下是一个函数,而在另一种情况下是一个字符串。谁能给我解释一下?

http://plnkr.co/edit/hSdQcRnvYn16ZeeJyPaM?p=preview

app = angular.module('app', []);
app.controller('mainCtrl', MainCtrl);

function MainCtrl($scope) {
    $scope.myColor1 = 'blue';
    $scope.myColor2 = 'blue';

    $scope.$watch(function(scope) {
            return scope.myColor1;
        },
        function(newValue, oldValue) {
            $scope.myStyle = 'color:' + $scope.myColor1
        }
    );
}


app.directive('fontColor', FontColor);
function FontColor() {
    return {
        restrict: 'A',
        link: function(scope, el, attrs) {
            scope.$watch(attrs['fontColor'], function(newVal) {
                console.log(newVal)
                el.css('color', newVal)
            })

        }
    }
}

HTML:

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css" />
    <link data-require="bootstrap-css@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script data-require="angular.js@1.4.5" data-semver="1.4.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body ng-app="app" ng-controller="mainCtrl" class="container" style="padding-top:30px">

    <div style="{{myStyle}}">color1</div>
    <input type="text" ng-model='myColor1'>
    <br><br>

    <div font-color="myColor2">color2</div>
    <input type="text" ng-model="myColor2">
</body>

</html>

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-watch


    【解决方案1】:

    这就是 $watch 在 Angular 中的定义方式。你可以在这里查看它的文档:$watch doc

    它指出$watch 的第一个参数可以是以下之一:

    • string:计算为表达式,或
    • function(scope):以当前作用域为参数调用

    【讨论】:

      猜你喜欢
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      相关资源
      最近更新 更多