Angular script won't run when first loaded - angularjs

On page load the console log prints but the toggleClass/click won't work I even use angular.element but it has the same result.I need to change state in order for the toggleClass to work.I dunno what's wrong in my code.
.run(['$rootScope', function ($rootScope) {
console.log('test');//this prints test and it's ok
//this part won't load at the first loading of page.
$('.toggle-mobile').click(function(){
$('.menu-mobile').toggle();
$(this).toggleClass('toggle-click');
});
//....
}])
even doing it this way doesn't work.
$rootScope.$on('$viewContentLoaded', function () {
angular.element('.toggle-mobile').on('click', function (event) {
angular.element(this).toggleClass('toggle-click');
angular.element('.menu-mobile').toggle();
event.preventDefault();
});
});

The Angular way to render items is different from "On DOM Ready" that is why we need to treat these as 2 separate things.
Angular could render items later on even after DOM is ready, this could happen for example if there is an AJAX call($http.get) and that is why a directive may be the recommended approach.
Try something like this:
<body ng-controller="MainCtrl">
<div toggle-Me="" class="toggle-mobile"> Sample <div class="menu-mobile">Sample 2</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', function ($scope) {}]);
myApp.directive("toggleMe", function() {
return {
restrict: "A", //A - means attribute
link: function(scope, element, attrs, ngModelCtrl) {
$(element).click(function(){
$('.menu-mobile').toggle();
$(this).toggleClass('toggle-click');
});
}
};
});
...
By declaring the directive myApp.directive("toggleMe",... as an attribute toggle-Me="" every time angular generates the input element it will execute the link function in the directive.
Disclaimer: Since the post lacks from a sample html I made up something to give an idea how to implement the solution but of course the suggested html is not part of the solution.

Related

Angular class change directive doesn't work

I want to add a directive that will do something when an element class is changed.
My directive is:
(function (angular) {
angular.module('myApp')
.directive('myClassWatch', myClassWatch);
function myClassWatch() {
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
scope.$watch(function () {
return element.attr('class');
}, function (newValue, oldValue) {
debugger;
if(oldValue !== newValue)
console.log('class changed from ' + oldValue + ' to ' + newValue);
});
}
}
}
})(angular);
The html is:
<div class="top-icons-item popup-container popup-link-container" my-class-watch>
</div>
I do some actions elsewhere that toggles the class "open" in my div element - it is visible in the html - yet the debugger is never called (also no console logs of course). I can see that the link function is called on page load and the debugger also stops, but thats only on page load and not afterwards when I actually do actions that adds another class.
I have read several issued here before including Directive : $observe, class attribute change caught only once but I can't understand why I don't get the same result. What can I do to try check why this occures?
Update: The class change is made using jQuery not in a controller but in an old jquery watches code. May this be cause? could angular be unaware of class change when its not done from an angular code?
Wrap your jQuery code into $apply.
It similar to you are making changes to $scope out of angular context(jquery ajax, setTimeout, etc). Use $apply to make angular know about the changes done.
angular.element(document.getElementById('app')).injector().invoke(['$compile', '$rootScope', function($compile, $rootScope) {
$rootScope.$apply(function() {
//your jquery code goes here...
var a = document.getElementById('abc');
angular.element(a).addClass('hello');
});
}]);

AngularJS: Can't call onClick() when using ng-bind-html [duplicate]

I've included a Plunker here: http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=preview
I'm trying to add a button to the DOM and when clicked should execute the function bound to it. In this case it should alert "testing". Here is the code.
controller
app.controller('MainCtrl', function($scope, $sce) {
$scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');
$scope.testAlert = function () {
alert('testing')
};
});
HTML
<body ng-controller="MainCtrl">
<div ng-bind-html="trustedHtml"></div>
</body>
$sce.trustAsHtml and ng-bind-html are not meant to build HTML with directives. This technique will not work.
This is because angular works by first compiling and then linking. See the conceptual overview for a good explaination.
In short, by the time you link the HTML defined in your trustAsHtml, it is too late for angular to compile (and therefore understand) the ng-click directive.
In order to dynamically add HTML, you should be looking at the $compile service (and/or directives). Docs are here.
For Angular 1.6.1, I found a solution that worked for me.
template:
<div ng-bind-html="trustAsHtml(content);" init-bind> </div>
In controller:
$scope.trustAsHtml = function(string) {
return $sce.trustAsHtml(string);
};
Directive:
.directive('initBind', function($compile) {
return {
restrict: 'A',
link : function (scope, element, attr) {
attr.$observe('ngBindHtml',function(){
if(attr.ngBindHtml){
$compile(element[0].children)(scope);
}
})
}
};
})

Angular dynamically created directive not executing

Plnkr sample: [http://plnkr.co/edit/jlMQ66eBlzaNSd9ZqJ4m?p=preview][1]
This might not be the proper "Angular" way to accomplish this, but unfortunately I'm working with some 3rd party libraries that I have limited ability to change. I'm trying to dynamically create a angular directive and add it to the page. The process works, at least in the sense where the directive element gets added to the DOM, HOWEVER it is not actually executed - it is just a dumb DOM at this point.
The relevant code is below:
<div ng-app="myModule">
<div dr-test="Static Test Works"></div>
<div id="holder"></div>
<a href="#" onclick="addDirective('Dynamic test works')">Add Directive</a>
</div>
var myModule = angular.module('myModule', []);
myModule.directive('drTest', function () {
console.log("Directive factory was executed");
return {
restrict: 'A',
replace: true,
link: function postLink(scope, element, attrs) {
console.log("Directive was linked");
$(element).html(attrs.drTest);
}
}
});
function addDirective(text){
console.log("Dynamically adding directive");
angular.injector(['ng']).invoke(['$compile', '$rootScope',function(compile, rootScope){
var scope = rootScope.$new();
var result = compile("<div dr-test='"+text+"'></div>")(scope);
scope.$digest();
angular.element(document.getElementById("holder")).append(result);
}]);
}
</script>
While appending the directive to DOM you need to invoke with your module as well in the injector, because the directive drTest is available only under your module, so while creating the injector apart from adding ng add your module as well. And you don't really need to do a scope apply since the element is already compile with the scope. You can also remove the redundant $(element).
angular.injector(['ng', 'myModule']).invoke(['$compile', '$rootScope',function(compile, rootScope){
var scope = rootScope.$new();
var result = compile("<div dr-test='"+text+"'></div>")(scope);
angular.element(document.getElementById("holder")).append(result);
}]);
Demo

Executing code at the end of angular initialization, and ngCloak display

I have a webpage written in angular with an ngCloak directive. It is loaded in a dynamically sized iframe with pym.js.
The trouble is that the page does not appear unless I resize the browser or trigger a resize event, or call pymChild.sendHeight() after the page loads.
I don't see any events associated with ngCloak though. Is there an angular event for "page is rendered, controllers are initialized"?
There is the $timeout service:
$timeout(function() {
// this code will execute after the render phase
});
You could write a directive that execute a callback in postLink function, since the postLink will be called last in the $compile life cycle.
.directive('onInitialized', function ($parse) {
return {
restrict: 'A',
priority: 1000, // to ensure that the postLink run last.
link: function postLink(scope, element, attrs) {
$parse(attrs.onInitialized)(scope);
}
}
});
and place it at the element that you would like to know when it and all its template-ready decendants have got compiled, for example:
<body ng-controller="MainCtrl" on-initialized="hello()">
and in the MainCtrl controller:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.hello = function () {
console.log('Hello ' + $scope.name);
};
})
For template-ready, I mean all directives except: directives with templateUrl and the template haven't ready in the $templateCache yet, since they will get compiled asynchronously.
Hope this helps.

Restarted initialization angular when updating DOM

I have page:
<div>111</div><div id="123" ng-init='foo=555'>{{foo}}</div>
in browser:
111
555
Code js refresh id=123 and get new html. I get:
<div id="123" ng-init='foo="444new"'><span>..</span><b>NEW TEXT<b> {{foo}}</div>
in browser
111
...NEW TEXT {{foo}}
I want get in browser:
111
...NEW TEXT 444new
Is it possible to re-run the initialization angular in this situation?
DEMO: jsfiddle.net/UwLQR
Solution for me: http://jsbin.com/iSUBOqa/8/edit - this BAD PRACTICE!
UPD two months later: My God, what nonsense I wrote. :(
See my notes in the included code and the live demo here (click).
The two reasons that angular will not register data-binding or directives are that the element isn't compiled, or the change happens outside of Angular. Using the $compile service, the compile function in directives, and $scope.$apply are the solutions. See below for usage.
Sample markup:
<div my-directive></div>
<div my-directive2></div>
<button id="bad-button">Bad Button!</button>
Sample code:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.foo = '123!';
$scope.bar = 'abc!';
//this is bad practice! just to demonstrate!
var badButton = document.getElementById('bad-button');
badButton.addEventListener('click', function() {
//in here, the context is outside of angular, so use $apply to tell Angular about changes!
$scope.$apply($scope.foo = "Foo is changed!");
});
});
app.directive('myDirective', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
//when using a link function, you must use $compile on the element
var newElem = angular.element('<div>{{foo}}</div>');
element.append(newElem);
$compile(newElem)(scope);
//or you can use:
//$compile(element.contents())(scope);
}
};
});
app.directive('myDirective2', function($compile) {
return {
restrict: 'A',
compile: function(element, attrs) {
//compile functions don't have access to scope, but they automatically compile the element
var newElem = angular.element('<div>{{bar}}</div>');
element.append(newElem);
}
};
});
Update based on your comment
It makes me cringe to write this, but this is what you would need to make that code work.
var elem = document.getElementById('123');
elem.innerHTML = "<div ng-init=\"foo='qwe123'\">{{foo}}</div>";
$scope.$apply($compile(elem)($scope));
Just as I said, you need to compile the element AND, since that is in an event listener, you need to use $apply as well, so that Angular will know about the compile you're doing.
That said, if you're doing anything like this at all, you REALLY need to learn more about angular. Anything like that should be done via directives and NEVER with any direct DOM manipulation.
Try next:
$scope.$apply(function() {
// your js updates here..
});
or
$compile('your html here')(scope);
Look $compile example at bottom of page.

Resources