处理角度指令“渲染后”的正确方法

时间:2014-02-07 16:00:00

标签: angularjs angularjs-directive

我有一个指令,我想在其中应用jQuery插件。插件需要在初始化期间评估元素值。但是指令中的“链接”函数在Angular完全处理元素之前运行。

使用$ timeout是否在呈现元素后查看元素的正确方法?应该延迟什么?您如何知道这种超时将在不同处理能力的系统和浏览器之间保持一致?

http://jsfiddle.net/fergal_doyle/DnrEm/3/

HTML:

<div ng-app="app" id="ng-app" ng-controller="test">
    <div ng-repeat="item in list">
        <label>{{item.title}}
            <input type="checkbox" someplugin  ng-checked="item.checked">
        </label>
    </div>
</div>

JS:

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

app.controller("test", function ($scope) {
    $scope.list = [{
        title: "A",
        checked: true
    }, {
        title: "B",
        checked: false
    }, {
        title: "C",
        checked: true
    }];
});

app.directive("someplugin", function ($timeout) {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {

            // too soon
            console.log($(element).prop("checked"));

            // works
            $timeout(function(){
             console.log($(element).prop("checked"));
            },0);

        }
    };
});

1 个答案:

答案 0 :(得分:0)

请改为尝试:

app.directive("someplugin", function () {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            // works
            scope.$watch(attrs.ngChecked,function(value){
               console.log(value);
            });
        }
    };
});

DEMO

当使用像angular这样的mvc结构时,我们不应该在角度更新视图时以我们不应该关心来听取视图的变化。

我们应该倾听模型,因为模型是我们存储应用状态的位置。

相关问题