angularjs,如何将父范围隔离变量传递给指令,并观察变量值

时间:2016-03-08 17:56:41

标签: angularjs typescript

我正在尝试将父控制器变量searchText连接到指令。 我真的希望这样做,我的模板也可以连接到同一个变量。它是一个简单的文本字段。

最初,我认为我需要创建一个手表,并手动设置变量,但事实证明链接工作正常。

我正在努力理解为什么手表会执行一次,而不是再次执行。

我有一个工作 _.groupBy() ,手表会记录到控制台。

HTML

<div ng-app="testApp">
  <div ng-controller="TestController">
    <div class="container">
      <span>TEXT :: {{searchText.searchText}}</span>          
      <div data-locate="locate" search="searchText">SB:{{searchTextBox}}</div>
    </div>
  </div>
</div>

控制器。

export class TestController {
    static $inject = ["$scope", "$timeout", "$log"];
    constructor($scope: any, $timeout: any, public $log: any) {
        $scope.searchText = { searchText: 'initial' };
        $timeout(() => $scope.searchText.searchText = 'new value....');
    }
}

指令

export class Locate {
    public restrict: string = "A";
    public template: string = "<input class='form-control' name='SearchText' type='text' ng-model='searchTextBox.searchText' />";
    public scope: any =
    {
        search: "=",
    }
    constructor(public $log: any) {            
    }
    public link: Function = ($scope: any, element: any) => {                       $scope.searchTextBox = 'a';
        // this code links the searchTextBox to the scope.
        $scope.searchTextBox = $scope.search;
        this.$log.log($scope.search);

         $scope.$watch('search', (o, n) => {

            // this watch only get's called once, and never again.

            this.$log.log(`watch called ${JSON.stringify(o)} :: ${JSON.stringify(n)}`);
            if (n) {
                this.$log.log(`watch updating ${JSON.stringify(n)}`);                    

                // it turns out the below code is not necessary, but
                // it only gets' called once, even when the value changes.
                $scope.searchTextBox = n;
            }
        });
    }          
    static factory(): any {
        const directive = ($log: any) => new Locate($log);
        directive.$inject = ['$log'];
        return directive;
    }    
}
Test.testApp.directive('locate', Locate.factory());
Test.testApp.controller('TestController', TestController);

2 个答案:

答案 0 :(得分:0)

如果您使用控制器,则需要在html中指定它。

尝试:

<body ng-controller="AController as td">
    <div locate searchText="td.searchText">
    </div>
</body>

答案 1 :(得分:0)

手表需要在手表上包含额外的布尔true值才能进行深度比较。

     $scope.$watch('search', (o, n) => {

        // this watch only get's called once, and never again.

        this.$log.log(`watch called ${JSON.stringify(o)} :: ${JSON.stringify(n)}`);
        if (n) {
            this.$log.log(`watch updating ${JSON.stringify(n)}`);                    

            // it turns out the below code is not necessary, but
            // it only gets' called once, even when the value changes.
            $scope.searchTextBox = n;
        }
    }, true); // the true is necessary