【问题标题】:watch on directive attribute监视指令属性
【发布时间】:2018-02-11 22:26:06
【问题描述】:

我想监视 max,如果 max 的值发生变化,那么它应该提醒

<div ng-controller='MyController' ng-app="myApp">
<div>{{title}}</div>
<input id='txt' type='text' max="{{max}}" value="{{max}}" foo/>
<input type="button" ng-click="changeMax()" value='change max' />

 scope: {
        max: '@',
    },
    link: function(scope, element, attrs) {
        /*scope.$watch(attrs.max, function() {
            alert('max changed to ' + max);
        });*/

        attrs.$observe('max', function(val) {
            alert('max changed to ' + max);
        });
    }

我不知道我在做什么错误。我尝试了 $watch 和 $observe 但没有成功。 请任何人都可以提供帮助。

JS FIDDLE demo

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-watch


    【解决方案1】:

    请检查此工作代码。

    var app = angular.module('myApp', []);
    
    app.directive('foo', function() {
        return {
            restrict: 'EA',
            scope: {
                max: '@',
            },
            link: function(scope, element, attrs) {
                /*scope.$watch(attrs.max, function() {
                    alert('max changed to ' + max);
                });*/
    
                attrs.$observe('max', function(val) {
                    alert('max changed to ' + val);
                });
            }
        }
    });
    
    app.controller('MyController', ['$scope', function($scope) {
        $scope.title = 'Hello world';
        $scope.max = 4;
        $scope.changeMax = function() {
            $scope.max += Math.floor(Math.random() * 10);
        }
    }]);
        
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js" ></script>
       <div ng-controller='MyController' ng-app="myApp">
            <div>{{title}}</div>
            <input id='txt' type='text' max="{{max}}" value="{{max}}" foo/>
            <input type="button" ng-click="changeMax()" value='change max' />
        </div>

    【讨论】:

    • foo 指令:刚刚移除 $watch 并替换了 alert('max changed to ' + max); by alert('max 变为 ' + val);
    • @VarunSukheja:如果它解决了您的问题,请将其标记为答案
    • 将 $watch 作为依赖项有什么问题?
    • 它显示此错误“未知提供者:$watchProvider
    • 你可以使用$watch作为$scope.$watch
    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多