这是我的指令的样子
//noinspection JSCheckFunctionSignatures
angular.module('notificationDirective', []).directive('notification', function ($timeout) {
//noinspection JSUnusedLocalSymbols
return {
restrict: 'E',
replace: true,
scope: {
ngModel: '@'
},
template: '<div class="alert fade" bs-alert="ngModel"></div>',
link: function (scope, element, attrs) {
scope.$watch('message', function () {
console.log('message now: ' + JSON.stringify(scope.message));
// element.show();
// //noinspection JSUnresolvedFunction
// $timeout(function () {
// //element.empty();
// element.fadeOut("slow");
// }, 2000);
});
}
}
});
这是我的控制器
function NotificationController($scope) {
$scope.message = {};
console.log('notification activated');
$scope.invite = function() {
console.log("submitting invite for " + $scope.email);
$scope.message.title = 'hello';
// console.log('message now is ' + JSON.stringify($scope.message, null, 2));
}
}
以下是我如何使用它
<form class="pure-form" data-ng-controller="NotificationController">
<input type="text" class="pure-input-1-2" placeholder="Email"
data-ng-model="email">
<button type="submit"
class="pure-button notice pure-button-xlarge"
data-ng-click="invite()">Invite me
</button>
</form>
<notification data-ng-model="message"></notification>
我想要什么
- 每当scope.message
中NotificationController
发生变化时值,该指令都会有新值,以便我可以在网页上发出警告
我不明白
我好像不明白$scope.$watch
是如何运作的
请帮忙
答案 0 :(得分:2)
你犯了几个错误:
以下是您的样本:
HTML:
<body>
<div id="my-app" data-ng-app="myApp">
<form class="pure-form" data-ng-controller="NotificationController">
<input type="text" class="pure-input-1-2" placeholder="Email" data-ng-model="email" />
<button type="submit"
class="pure-button notice pure-button-xlarge"
data-ng-click="invite()">Invite me
</button>
<notification data-ng-model="message"></notification>
</form>
</div>
</body>
Javascript:
var myApp = angular.module('myApp', []);
myApp.directive('notification', function() {
return {
restrict: 'E',
replace: true,
scope: {
ngModel: '='
},
template: '<div class="alert fade" bs-alert="ngModel"></div>',
link: function (scope, element, attrs) {
scope.$watch('ngModel', function () {
console.log('message now: ' + JSON.stringify(scope.ngModel));
// element.show();
// //noinspection JSUnresolvedFunction
// $timeout(function () {
// //element.empty();
// element.fadeOut("slow");
// }, 2000);
}, true);
}
}
});
myApp.controller('NotificationController', ['$scope', function($scope) {
$scope.message = {};
console.log('notification activated');
$scope.invite = function() {
console.log("submitting invite for " + $scope.email);
$scope.message.title = 'hello';
// console.log('message now is ' + JSON.stringify($scope.message, null, 2));
};
}]);
看到这个小提琴:http://jsfiddle.net/77Uca/15/
答案 1 :(得分:0)
我相信你需要在你的指令定义中:
ngModel: '='
而不是:
ngModel: '@'
如果您想使用“@”,您的观点应为:
<notification data-ng-model="{{message}}"></notification>
同样在$watch
你应该关注的是ngModel
,而不是message
。