gpt4 book ai didi

AngularJS 指令检测在模型属性更改中传递

转载 作者:行者123 更新时间:2023-12-04 02:06:25 25 4
gpt4 key购买 nike

我有一个独立作用域的指令。我想检测作为父范围变量的属性的更改。

到目前为止,我有以下内容:

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


app.controller("ctrl", function($scope, $timeout) {

$timeout(function() {
console.log("called");

$scope.isReady = true;
$scope.$apply();
}, 2000);


});

app.directive("car", function($log) {
return {
scope: {
make: "=carMake"
},
restrict: 'E',
template: "<strong ng-bind='make'></strong>",
link: function(scope, elem, attrs) {

scope.$watch(attrs.shouldDo, function(value) {
var val = value || null;
if (val) {
$log.info(scope.$eval(attrs.shouldDo));
}
}, true);

}
}
});

http://fiddle.jshell.net/8Qhuk/

如果我将作用域设置为 false 它会起作用,但是我需要它来处理一个独立的作用域。

最佳答案

只需将 scope 部分写成:

 scope: {
make : "=carMake",
shouldDo: '='
},

修复演示 Fiddle

指令示例:

app.directive("car", function($log) {
return {
scope: {
make: "=carMake",
shouldDo: '='
},
restrict: 'E',
template: "<strong ng-bind='make'></strong>",
link: function(scope, elem, attrs) {

scope.$watch(function() {
return scope.shouldDo
},
function(newValue, oldValue) {
var val = newValue || null;
if (val) {
$log.info(scope.shouldDo);
}
});
}
}
});

watch 中,我们只监听一个变量。你不需要 true 标志


顺便说一句,你可以使用绑定(bind)一次只读

 scope: {
make : "=carMake",
shouldDo: '@'
},

当 HTML 时:

<car car-make="make" should-do="{{isReady}}"></car>

演示 2 Fiddle

关于AngularJS 指令检测在模型属性更改中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24883093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com