我创建了一个自定义指令,并使用了双向绑定(=)
但我想要观察当模型在指令中改变时控制器中的变化。
警报应该在用户更改输入时出现,但警报只在开始时出现一次。
我的javascript
var myApp = angular.module('myApp', [])
.controller("myCtrl", function ($scope) {
$scope.test = "myValue";
$scope.$watch('myValue', function () {
alert('hey, myVar has changed!');
});
})
.directive('myDirective', function () {
return {
restrict: 'EA',
scope: {
myModel: '=ngModel'
},
template: '<input ng-model="myModel"/>'
}
});和html
<div ng-app="myApp">
<div ng-controller="myCtrl">{{test}}
<my-directive ng-model="test"></my-directive>
</div>
</div>http://jsfiddle.net/c7nbk8uq/
发布于 2014-12-05 19:37:51
你看错了变量吗?
$scope.$watch('test', function() {
alert('hey, myVar has changed!');
});发布于 2014-12-05 19:38:01
你把“myValue”和“test”拼错了。
$scope.$watch('test', function() {
alert('hey, myVar has changed!');
});http://jsfiddle.net/pmydr7qp/
https://stackoverflow.com/questions/27315039
复制相似问题