虽然在角度指令(例如ng-change)中使用Angularfire的$ save()方法同步数据没有问题,例如:
<input ng-model="contact.name" ng-change="contact.$save()"/>
当我尝试在我自己的自定义指令中执行相同操作时,会出现问题。我已经删除了我的应用程序来指定问题:
这是带有依赖项的index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<!--AngularJS-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<!--ngSanitize-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.2/angular-sanitize.min.js"></script>
<!--Firebase-->
<script src="https://cdn.firebase.com/js/client/2.2.1/firebase.js"></script>
<!--AngularFire-->
<script src="https://cdn.firebase.com/libs/angularfire/1.1.4/angularfire.min.js"></script>
<!--Controller for the application-->
<script src="controller.js"></script>
</head>
<body ng-controller="appCtrl">
<p editable="contact.name" field-type="text"></p>
</body>
</html>
我们只给了一个带有联系人姓名的字段。 然后是有问题的controller.js,我在firebase中创建了一个名为“person1”的id,只包含一个键“name”:
app = angular
.module('myApp', ['firebase', 'ngSanitize'])
.controller('appCtrl', function($scope, $firebaseArray, $firebaseObject){
var contacts = new Firebase("https://contactsmgr.firebaseIO.com/contacts");
$scope.contact = $firebaseObject(contacts.child("person1"));
})
.directive('editable', function() {
return {
restrict: 'AE',
templateUrl: 'editable.html',
scope: {
value: '=editable',
field: '@fieldType'
},
controller: function($scope) {
$scope.editor = {
showing: false,
value: $scope.value
};
$scope.toggleEditor = function() {
$scope.editor.showing = !$scope.editor.showing;
$scope.field = ($scope.field) ? $scope.field : 'text';
};
$scope.save = function() {
$scope.value = $scope.editor.value;
$scope.value.$save();
$scope.toggleEditor();
};
},
}
});
只要在元素中使用“editable”,就会调用该指令。它首先加载“editable.html”部分来替换它:
<!-- EDITOR.SHOWING SET TO FALSE BY DEFAULT -->
<div ng-hide="editor.showing">
<span ng-bind-html="value"></span>
<button ng-click="toggleEditor()">Edit</button>
</div>
<!-- EDITOR THAT APPEARS AFTER CLICKING "EDIT" BUTTON -->
<div ng-show="editor.showing">
<input type="{{field}}" ng-model="editor.value">
</div>
<!-- EDITOR BUTTONS THAT APPEAR TOGETHER WITH EDITOR-->
<button ng-click="save()">Save</button>
<button ng-click="toggleEditor()">Cancel</button>
我们的想法是将值(与可编辑指令的值绑定)保存到Firebase,并在“controller.js”中使用$ scope.value。$ save()。相反,它会抛出此错误:
TypeError: $scope.value.$save is not a function
以下是在plunkr上粘贴的相同代码:
https://plnkr.co/edit/hdW731LjSuY0a1tscW6T?p=preview
该指令的孤立$范围是否有错?