html
<div class="result" ng-controller="test">
<div>{{result}}</div>
<a ng-href="{{result}}"></a>
</div>
JS
App.controller('AppCtrl', function AppCtrl($scope){
$scope.result = "www.google.com";
}
在一个 jquery 文件中,由于某种原因我无法修改,一些代码更改了 href 的值,例如:
$('.result>a').attr('href','www.youtube.com');
我希望控制器中 $scope.result 的值也从“www.google.com”更改为“www.youtube.com”。但是在div
jquery 代码之后结果值没有改变。我是否需要编写指令才能自己观看 href 属性?还是有其他方法可以使用 ng-href?我尝试自己编写指令,但没有奏效。我希望你能给我一个小例子。谢谢 :)
更新:
这是我的指令,它不起作用,在 $('.result>a').attr('href','www.youtube.com') 之后,控制台没有打印“更改!” 并且 $scope.result 没有改变:
APP.directive('result', function() {
return {
restrict: 'E',
scope: {
ngModel: '='
},
template: "<div class='result'><a ng-href='{{ngModel}}' href=''></a></div>",
replace: true,
require: 'ngModel',
link: function(scope, element, attrs) {
var $element = $(element.children()[0]);
scope.$watch($element.attr('href'), function(newValue) {
console.log("change!");
scope.ngModel = newValue;
})
}
};
});
再次更新:仍然无法工作...
html:
<div class="result">
<a ng-href="{{result}}" ng-model="result" class="resulta"></a>
</div>
JS:
APP.directive('resulta', function() {
return {
restrict: 'C',
scope: {
ngModel: '='
},
link: function(scope, element, attrs) {
scope.$watch(attrs.href, function(newValue) {
console.log("change!");
scope.ngModel = newValue;
})
}
};
});