我有一个整个应用程序使用的全局搜索变量
newspaper.controller("MainController", function($scope) {
$scope.search = {query:''};
});
然后我有一个我想要绑定到$ scope.search
的contenteditable divapp.directive('search', function() {
return {
restrict: 'AE',
replace: true,
template: '<div ng-model="query" id="search"></div>',
scope: {
query: '='
},
controller: function($scope) {
// I want to watch the value of the element
$scope.$watch('query', function(newValue, oldValue){
console.log(newValue);
},true);
},
link: function(scope, element, attrs) {
// Medium JS content editable framework
new Medium({
element: element[0],
mode: Medium.inlineMode
});
}
}
});
当我在div中键入新值时手表没有触发,我想我仍然对如何将指令与模型链接感到困惑。这是HTML
<nav ng-controller="MainControllerr">
<search context="search.query"></np-search>
</nav>
答案 0 :(得分:0)
不要认为你需要watch
。在控制器中使用watch
函数无论如何都是不好的做法,因为它使它们真的难以测试。
这是我试图做的简化版本(我认为)。
<强>的index.html 强>
<!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.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
<script src="app.js"></script>
</head>
<body>
<nav ng-controller="MainController">
<pre>{{query}}</pre>
<search query="query"></search>
</nav>
</body>
</html>
<强> app.js 强>
var app = angular.module('plunker', []);
app.controller("MainController", function($scope) {
$scope.query = {value:''};
});
app.directive('search', function() {
return {
restrict: 'AE',
template: '<input ng-model="query.value" id="search"/>',
scope: {
query: '='
}
}
});
修改强>
如果你真的想使用内容可编辑的div,你必须尝试这样的事情:
此外,请参阅我已采用的SO question并修改代码以创建下面的演示。希望它有所帮助。
<强>的index.html 强>
<!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.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
<script src="app.js"></script>
</head>
<body>
<nav ng-controller="MainController">
<pre>{{query}}</pre>
<div search contenteditable="true" ng-model="query.value">{{ query.value }}</div>
</nav>
</body>
</html>
<强> app.js 强>
var app = angular.module(&#39; plunker&#39;,[]);
app.controller(&#34; MainController&#34;,function($ scope){ $ scope.query = {value:&#39; rrr&#39;}; });
app.directive('search', function() {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
element.bind('blur', function() {
scope.$apply(function() {
ctrl.$setViewValue(element.html());
});
});
element.html(ctrl.$viewValue);
}
}
});