[英]angularjs, how to pass parent scope isolated variable to a directive, and watch the variable value
我正在尝试将父控制器变量searchText
连接到指令。 我实际上希望以这样的方式进行操作,即我的模板也可以连接到同一变量。 这是一个简单的文本字段。
最初,我以为我需要创建一个手表,并手动设置变量,但事实证明链接仍然有效。
我在努力理解为什么手表执行一次,而不执行一次。
我在这里有一个可工作的codepen ,手表已记录在控制台上。
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);
如果使用controllerAs,则需要在html中指定它。
尝试:
<body ng-controller="AController as td">
<div locate searchText="td.searchText">
</div>
</body>
手表需要包括一个额外的布尔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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.