AngularJS:等待'链接'指令不起作用

时间:2016-09-24 10:00:35

标签: angularjs

在下面的源代码中,自定义指令的链接部分中的watch方法不起作用。我使用' link'在指令中,因为我必须更新DOM结构。

如何在指令的链接{}中获取手表每按一次按钮的时间?

编辑:我发现了错误的代码。见下文' ERROR'并且'正确'码。

此脚本上方的HTML是(单击按钮以增加变量):

<div ng-controller="AppController as vmx">
    <button ng-click="vmx.incrementFoo()">Increment Foo</button>:
    {{ vmx.fooCount }}.
    <div foo-count-updated></div>
</div>

角度代码:

angular.module( "myapp", [])
 .controller( "AppController", myAppController)
   .directive('showAlsoInCustomDirective', showAlsoInCustomDirective);

   // *** CONTROLLER
   function myAppController( $scope ) {
    var vm = this;
    vm.fooCount = 0;
    vm.copiedFooCount = 0; 

    // ERROR code: 
    // **vm.getFooCount** = function() { 
    //    return vm.fooCount;
    // }

    // CORRECT code: 
    getFooCount = function() { 
      return vm.fooCount;
    }
    vm.getFooCount = getFooCount; 

    vm.incrementFoo = incrementFoo;
    function incrementFoo() {
      ++vm.fooCount;
    }
  }

 // *** DIRECTIVE 
.directive('fooCountUpdated', fooCountUpdater);
function fooCountUpdater() {
    var indirectivecounter = 0; 
    getFooCountInDirective = function() { 
        return getFooCount();
    }
    var watcherFn = function (watchScope) {
        return getFooCountInDirective();
    }
    return { 
        link: function (scope, element, attrs) {
            scope.$watch(watcherFn, function (newValue, oldValue) {
                element.html( "Got the change: " + newValue);
            })
        }};
    }

完整的源代码放在这个文件中: https://plnkr.co/edit/J6nfLQ3dmLW0gDNXV0J5?p=preview

1 个答案:

答案 0 :(得分:0)

如上所述,解决方案很简单。它也在plunker文件中。

HTML:

<div ng-controller="AppController as vmx">
    <button ng-click="vmx.incrementFoo()">Increment Foo</button>:
    {{ vmx.fooCount }}.
    <div foo-count-updated></div>
</div>

角度代码:

angular.module( "myapp", [])
.controller( "AppController", function( $scope ) {
    var vm = this;
    vm.fooCount = 0;
    getFooCount = function() { 
        return vm.fooCount;
    }
    vm.getFooCount = getFooCount;
    vm.incrementFoo = incrementFoo;
    function incrementFoo() {
        ++vm.fooCount;
    }
})
.directive('fooCountUpdated', fooCountUpdater);
function fooCountUpdater() {
    var indirectivecounter = 0; 
    getFooCountInDirective = function() { 
        return getFooCount();
    }
    var watcherFn = function (watchScope) {
        return getFooCountInDirective();
    }
    return { 
        link: function (scope, element, attrs) {
            scope.$watch(watcherFn, function (newValue, oldValue) {
            element.html( "Got the change: " + newValue);
         })
    }};
 }