angularjs无法在下拉列表更改时更新指令

时间:2013-07-05 06:34:26

标签: javascript angularjs angularjs-directive

无法使用anuglar js更新下拉列表更改中的指令。 这是我的应用代码

html代码

<div ng-app="myApp" ng-controller="MyCtrl">
    <select ng-model="opt" ng-options="font.title for font in fonts" ng-change="change(opt)">
    </select>
    <p>
        {{opt}}</p>
    <br />
    <h3>
        Text Is
    </h3>
    <div id="tstDiv" testdir ct="ct">
    </div>
</div>

控制器和指令代码

angular.module("myApp", []).controller("MyCtrl", function ($scope) {
        $scope.fonts = [
    { title: "Arial", text: 'Url for Arial' },
    { title: "Helvetica", text: 'Url for Helvetica' }
];
        $scope.opt = $scope.fonts[0];
        $scope.change = function (option) {
            $scope.opt = option;
        }
    })
        .directive("testDir", function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    ct: '=ct'
                },
                link: function ($scope, $elm, $attr) {
                    document.getElementById('tstDiv').innerHTML = $scope.selectedTitle;
                }
            };
        });

这是小提琴http://jsfiddle.net/Cbqju/

2 个答案:

答案 0 :(得分:0)

看起来你会想要关注那个变量的变化 您的链接功能应该类似于

scope: {
    ct: '=ct',
    opt: '=opt'
},
link: function ($scope, $elm, $attr) {
    $scope.$watch('opt', function(newOpt, oldOpt) {
        document.getElementById('tstDiv').innerHTML = newOpt.title;
    });
}

答案 1 :(得分:0)

根据@Ajaybeniwal,这里的评论是工作plunker