呼叫服务,我有我AngularJS内部应用程序下面的指令,服务和控制器。该服务在指令和此控制器(以及在我的应用程序中使用相同服务的其他控制器)之间通用。如控制器内部所示,我观察服务的变化,而在指令中,我与服务进行通信以更新它。出于某种原因,我不知道该指令没有更新我的服务,所以有人可以告诉我什么,我做错了什么?由于AngularJS来自自定义指令
控制器:
myapp.controller('ClientsCtrl', function ($scope, UserSvc) { $scope.showForm = UserSvc.frmOpened; $scope.$watch(function() { return UserSvc.frmOpened; }, function() { $scope.showForm = UserSvc.frmOpened; console.log('Changed... ' + $scope.showForm); }); });
服务
myapp.factory('UserSvc', function ($log, $q, $http) { return { frmOpened: false }; });
指令:
myapp.directive('myDirective', ['UserSvc', function (UserSvc) { return { restrict: 'A', link: function (scope, element, attrs) { angular.element(element).on("click", function() { var parentElement = $(this).parent(); if (parentElement.hasClass('sample')) UserSvc.frmOpened = true; //This code never update the service } else { UserSvc.frmOpened = false; //This code never update the service } return false; }); } }; }]);
非常感谢,现在的工作,但有一个滞后(如1-2次,但很明显)的时候我与指令和表单的按钮点击显示基于对控制器的更改showForm之间,所以你碰巧知道这是由于使用手表NG-秀监控对showForm或者是由于应用或整个结构本身?由于 – MChan
对不起,真的很难说没有看到所有涉及的代码。 – tasseKATT