如何在自定义指令上加载数据后执行 ng-change
How to execute ng-change after loading data on custom directive
我在 angular js 中写了一个自定义指令,在 plnkr 中可用,
当加载指令时,它已经调用了 MainCtrl 上的 changed() 函数,我需要停止 changed() 函数,直到数据加载到指令中,之后,它应该开始观察指令内输入的变化,顺便说一句,changed() 函数应该在 MainCtrl 中,因为它在 example 中,所以有什么方法可以在将数据加载到指令之前停止执行 ng-change 吗?
这是代码:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "someName";
$scope.statusText = "unChanged";
$scope.changed = function(){
$scope.statusText = "changed";
};
});
app.directive("myDirective", function () {
return {
restrict: 'EA',
scope: {
ngModel: "=",
ngChange: "="
},
templateUrl: "template.html",
link: function ($scope, elem, attrs) {
}
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<my-directive ng-model="name" ng-change="changed()"></my-directive>
<p>{{statusText}}</p>
<script type="text/ng-template" id="template.html">
<input type="text" ng-model="ngModel" ng-change="ngChange" >
</script>
</body>
</html>
- 你必须更改指令的接收 属性
ngModel
和 ngChange
,它与 angularhs 的内置指令冲突。
- 如果要从指令中调用函数,请使用“&”
参考这个 plunker(我刚刚从你的问题中分叉)。
我在 angular js 中写了一个自定义指令,在 plnkr 中可用, 当加载指令时,它已经调用了 MainCtrl 上的 changed() 函数,我需要停止 changed() 函数,直到数据加载到指令中,之后,它应该开始观察指令内输入的变化,顺便说一句,changed() 函数应该在 MainCtrl 中,因为它在 example 中,所以有什么方法可以在将数据加载到指令之前停止执行 ng-change 吗? 这是代码:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "someName";
$scope.statusText = "unChanged";
$scope.changed = function(){
$scope.statusText = "changed";
};
});
app.directive("myDirective", function () {
return {
restrict: 'EA',
scope: {
ngModel: "=",
ngChange: "="
},
templateUrl: "template.html",
link: function ($scope, elem, attrs) {
}
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<my-directive ng-model="name" ng-change="changed()"></my-directive>
<p>{{statusText}}</p>
<script type="text/ng-template" id="template.html">
<input type="text" ng-model="ngModel" ng-change="ngChange" >
</script>
</body>
</html>
- 你必须更改指令的接收 属性
ngModel
和ngChange
,它与 angularhs 的内置指令冲突。 - 如果要从指令中调用函数,请使用“&”
参考这个 plunker(我刚刚从你的问题中分叉)。